babylon.max.js 4.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248
  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. var vertexSource;
  221. var fragmentSource;
  222. if (baseName.vertexElement) {
  223. vertexSource = document.getElementById(baseName.vertexElement);
  224. if (!vertexSource) {
  225. vertexSource = baseName.vertexElement;
  226. }
  227. }
  228. else {
  229. vertexSource = baseName.vertex || baseName;
  230. }
  231. if (baseName.fragmentElement) {
  232. fragmentSource = document.getElementById(baseName.fragmentElement);
  233. if (!fragmentSource) {
  234. fragmentSource = baseName.fragmentElement;
  235. }
  236. }
  237. else {
  238. fragmentSource = baseName.fragment || baseName;
  239. }
  240. var finalVertexCode;
  241. this._loadVertexShaderAsync(vertexSource)
  242. .then(function (vertexCode) {
  243. return _this._processIncludesAsync(vertexCode);
  244. })
  245. .then(function (vertexCodeWithIncludes) {
  246. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  247. return _this._loadFragmentShaderAsync(fragmentSource);
  248. })
  249. .then(function (fragmentCode) {
  250. return _this._processIncludesAsync(fragmentCode);
  251. })
  252. .then(function (fragmentCodeWithIncludes) {
  253. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  254. if (baseName) {
  255. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  256. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  257. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  258. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  259. }
  260. else {
  261. _this._vertexSourceCode = finalVertexCode;
  262. _this._fragmentSourceCode = migratedFragmentCode;
  263. }
  264. _this._prepareEffect();
  265. });
  266. }
  267. Object.defineProperty(Effect.prototype, "key", {
  268. /**
  269. * Unique key for this effect
  270. */
  271. get: function () {
  272. return this._key;
  273. },
  274. enumerable: true,
  275. configurable: true
  276. });
  277. /**
  278. * If the effect has been compiled and prepared.
  279. * @returns if the effect is compiled and prepared.
  280. */
  281. Effect.prototype.isReady = function () {
  282. return this._isReady;
  283. };
  284. /**
  285. * The engine the effect was initialized with.
  286. * @returns the engine.
  287. */
  288. Effect.prototype.getEngine = function () {
  289. return this._engine;
  290. };
  291. /**
  292. * The compiled webGL program for the effect
  293. * @returns the webGL program.
  294. */
  295. Effect.prototype.getProgram = function () {
  296. return this._program;
  297. };
  298. /**
  299. * The set of names of attribute variables for the shader.
  300. * @returns An array of attribute names.
  301. */
  302. Effect.prototype.getAttributesNames = function () {
  303. return this._attributesNames;
  304. };
  305. /**
  306. * Returns the attribute at the given index.
  307. * @param index The index of the attribute.
  308. * @returns The location of the attribute.
  309. */
  310. Effect.prototype.getAttributeLocation = function (index) {
  311. return this._attributes[index];
  312. };
  313. /**
  314. * Returns the attribute based on the name of the variable.
  315. * @param name of the attribute to look up.
  316. * @returns the attribute location.
  317. */
  318. Effect.prototype.getAttributeLocationByName = function (name) {
  319. var index = this._attributesNames.indexOf(name);
  320. return this._attributes[index];
  321. };
  322. /**
  323. * The number of attributes.
  324. * @returns the numnber of attributes.
  325. */
  326. Effect.prototype.getAttributesCount = function () {
  327. return this._attributes.length;
  328. };
  329. /**
  330. * Gets the index of a uniform variable.
  331. * @param uniformName of the uniform to look up.
  332. * @returns the index.
  333. */
  334. Effect.prototype.getUniformIndex = function (uniformName) {
  335. return this._uniformsNames.indexOf(uniformName);
  336. };
  337. /**
  338. * Returns the attribute based on the name of the variable.
  339. * @param uniformName of the uniform to look up.
  340. * @returns the location of the uniform.
  341. */
  342. Effect.prototype.getUniform = function (uniformName) {
  343. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  344. };
  345. /**
  346. * Returns an array of sampler variable names
  347. * @returns The array of sampler variable neames.
  348. */
  349. Effect.prototype.getSamplers = function () {
  350. return this._samplers;
  351. };
  352. /**
  353. * The error from the last compilation.
  354. * @returns the error string.
  355. */
  356. Effect.prototype.getCompilationError = function () {
  357. return this._compilationError;
  358. };
  359. /**
  360. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  361. * @param func The callback to be used.
  362. */
  363. Effect.prototype.executeWhenCompiled = function (func) {
  364. if (this.isReady()) {
  365. func(this);
  366. return;
  367. }
  368. this.onCompileObservable.add(function (effect) {
  369. func(effect);
  370. });
  371. };
  372. /** @ignore */
  373. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  374. if (BABYLON.Tools.IsWindowObjectExist()) {
  375. // DOM element ?
  376. if (vertex instanceof HTMLElement) {
  377. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  378. return Promise.resolve(vertexCode);
  379. }
  380. }
  381. // Base64 encoded ?
  382. if (vertex.substr(0, 7) === "base64:") {
  383. var vertexBinary = window.atob(vertex.substr(7));
  384. return Promise.resolve(vertexBinary);
  385. }
  386. // Is in local store ?
  387. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  388. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  389. }
  390. var vertexShaderUrl;
  391. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  392. vertexShaderUrl = vertex;
  393. }
  394. else {
  395. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  396. }
  397. // Vertex shader
  398. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  399. };
  400. /** @ignore */
  401. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  402. if (BABYLON.Tools.IsWindowObjectExist()) {
  403. // DOM element ?
  404. if (fragment instanceof HTMLElement) {
  405. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  406. return Promise.resolve(fragmentCode);
  407. }
  408. }
  409. // Base64 encoded ?
  410. if (fragment.substr(0, 7) === "base64:") {
  411. var fragmentBinary = window.atob(fragment.substr(7));
  412. return Promise.resolve(fragmentBinary);
  413. }
  414. // Is in local store ?
  415. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  416. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  417. }
  418. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  419. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  420. }
  421. var fragmentShaderUrl;
  422. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  423. fragmentShaderUrl = fragment;
  424. }
  425. else {
  426. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  427. }
  428. // Fragment shader
  429. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  430. };
  431. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  432. // Rebuild shaders source code
  433. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  434. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  435. vertexCode = prefix + vertexCode;
  436. fragmentCode = prefix + fragmentCode;
  437. // Number lines of shaders source code
  438. var i = 2;
  439. var regex = /\n/gm;
  440. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  441. i = 2;
  442. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  443. // Dump shaders name and formatted source code
  444. if (this.name.vertexElement) {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  447. }
  448. else if (this.name.vertex) {
  449. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  450. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  451. }
  452. else {
  453. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  454. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  455. }
  456. };
  457. ;
  458. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  459. var preparedSourceCode = this._processPrecision(sourceCode);
  460. if (this._engine.webGLVersion == 1) {
  461. return preparedSourceCode;
  462. }
  463. // Already converted
  464. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  465. return preparedSourceCode.replace("#version 300 es", "");
  466. }
  467. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  468. // Remove extensions
  469. // #extension GL_OES_standard_derivatives : enable
  470. // #extension GL_EXT_shader_texture_lod : enable
  471. // #extension GL_EXT_frag_depth : enable
  472. // #extension GL_EXT_draw_buffers : require
  473. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  474. var result = preparedSourceCode.replace(regex, "");
  475. // Migrate to GLSL v300
  476. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  477. result = result.replace(/attribute[ \t]/g, "in ");
  478. result = result.replace(/[ \t]attribute/g, " in");
  479. if (isFragment) {
  480. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  481. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  482. result = result.replace(/texture2D\s*\(/g, "texture(");
  483. result = result.replace(/textureCube\s*\(/g, "texture(");
  484. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  485. result = result.replace(/gl_FragColor/g, "glFragColor");
  486. result = result.replace(/gl_FragData/g, "glFragData");
  487. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  488. }
  489. return result;
  490. };
  491. Effect.prototype._processIncludesAsync = function (sourceCode) {
  492. var _this = this;
  493. return new Promise(function (resolve, reject) {
  494. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  495. var match = regex.exec(sourceCode);
  496. var returnValue = sourceCode;
  497. while (match != null) {
  498. var includeFile = match[1];
  499. // Uniform declaration
  500. if (includeFile.indexOf("__decl__") !== -1) {
  501. includeFile = includeFile.replace(/__decl__/, "");
  502. if (_this._engine.supportsUniformBuffers) {
  503. includeFile = includeFile.replace(/Vertex/, "Ubo");
  504. includeFile = includeFile.replace(/Fragment/, "Ubo");
  505. }
  506. includeFile = includeFile + "Declaration";
  507. }
  508. if (Effect.IncludesShadersStore[includeFile]) {
  509. // Substitution
  510. var includeContent = Effect.IncludesShadersStore[includeFile];
  511. if (match[2]) {
  512. var splits = match[3].split(",");
  513. for (var index = 0; index < splits.length; index += 2) {
  514. var source = new RegExp(splits[index], "g");
  515. var dest = splits[index + 1];
  516. includeContent = includeContent.replace(source, dest);
  517. }
  518. }
  519. if (match[4]) {
  520. var indexString = match[5];
  521. if (indexString.indexOf("..") !== -1) {
  522. var indexSplits = indexString.split("..");
  523. var minIndex = parseInt(indexSplits[0]);
  524. var maxIndex = parseInt(indexSplits[1]);
  525. var sourceIncludeContent = includeContent.slice(0);
  526. includeContent = "";
  527. if (isNaN(maxIndex)) {
  528. maxIndex = _this._indexParameters[indexSplits[1]];
  529. }
  530. for (var i = minIndex; i < maxIndex; i++) {
  531. if (!_this._engine.supportsUniformBuffers) {
  532. // Ubo replacement
  533. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  534. return p1 + "{X}";
  535. });
  536. }
  537. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  538. }
  539. }
  540. else {
  541. if (!_this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent = includeContent.replace(/\{X\}/g, indexString);
  548. }
  549. }
  550. // Replace
  551. returnValue = returnValue.replace(match[0], includeContent);
  552. }
  553. else {
  554. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  555. _this._engine._loadFileAsync(includeShaderUrl)
  556. .then(function (fileContent) {
  557. Effect.IncludesShadersStore[includeFile] = fileContent;
  558. return _this._processIncludesAsync(returnValue);
  559. })
  560. .then(function (returnValue) {
  561. resolve(returnValue);
  562. });
  563. return;
  564. }
  565. match = regex.exec(sourceCode);
  566. }
  567. resolve(returnValue);
  568. });
  569. };
  570. Effect.prototype._processPrecision = function (source) {
  571. if (source.indexOf("precision highp float") === -1) {
  572. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  573. source = "precision mediump float;\n" + source;
  574. }
  575. else {
  576. source = "precision highp float;\n" + source;
  577. }
  578. }
  579. else {
  580. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  581. source = source.replace("precision highp float", "precision mediump float");
  582. }
  583. }
  584. return source;
  585. };
  586. /**
  587. * Recompiles the webGL program
  588. * @param vertexSourceCode The source code for the vertex shader.
  589. * @param fragmentSourceCode The source code for the fragment shader.
  590. * @param onCompiled Callback called when completed.
  591. * @param onError Callback called on error.
  592. */
  593. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  594. var _this = this;
  595. this._isReady = false;
  596. this._vertexSourceCodeOverride = vertexSourceCode;
  597. this._fragmentSourceCodeOverride = fragmentSourceCode;
  598. this.onError = function (effect, error) {
  599. if (onError) {
  600. onError(error);
  601. }
  602. };
  603. this.onCompiled = function () {
  604. var scenes = _this.getEngine().scenes;
  605. for (var i = 0; i < scenes.length; i++) {
  606. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  607. }
  608. if (onCompiled) {
  609. onCompiled(_this._program);
  610. }
  611. };
  612. this._fallbacks = null;
  613. this._prepareEffect();
  614. };
  615. /**
  616. * Gets the uniform locations of the the specified variable names
  617. * @param names THe names of the variables to lookup.
  618. * @returns Array of locations in the same order as variable names.
  619. */
  620. Effect.prototype.getSpecificUniformLocations = function (names) {
  621. var engine = this._engine;
  622. return engine.getUniforms(this._program, names);
  623. };
  624. /**
  625. * Prepares the effect
  626. */
  627. Effect.prototype._prepareEffect = function () {
  628. var attributesNames = this._attributesNames;
  629. var defines = this.defines;
  630. var fallbacks = this._fallbacks;
  631. this._valueCache = {};
  632. var previousProgram = this._program;
  633. try {
  634. var engine = this._engine;
  635. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  636. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  637. }
  638. else {
  639. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  640. }
  641. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  642. if (engine.supportsUniformBuffers) {
  643. for (var name in this._uniformBuffersNames) {
  644. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  645. }
  646. }
  647. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  648. this._attributes = engine.getAttributes(this._program, attributesNames);
  649. var index;
  650. for (index = 0; index < this._samplers.length; index++) {
  651. var sampler = this.getUniform(this._samplers[index]);
  652. if (sampler == null) {
  653. this._samplers.splice(index, 1);
  654. index--;
  655. }
  656. }
  657. engine.bindSamplers(this);
  658. this._compilationError = "";
  659. this._isReady = true;
  660. if (this.onCompiled) {
  661. this.onCompiled(this);
  662. }
  663. this.onCompileObservable.notifyObservers(this);
  664. this.onCompileObservable.clear();
  665. // Unbind mesh reference in fallbacks
  666. if (this._fallbacks) {
  667. this._fallbacks.unBindMesh();
  668. }
  669. if (previousProgram) {
  670. this.getEngine()._deleteProgram(previousProgram);
  671. }
  672. }
  673. catch (e) {
  674. this._compilationError = e.message;
  675. // Let's go through fallbacks then
  676. BABYLON.Tools.Error("Unable to compile effect:");
  677. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  678. return " " + uniform;
  679. }));
  680. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  681. return " " + attribute;
  682. }));
  683. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  684. BABYLON.Tools.Error("Error: " + this._compilationError);
  685. if (previousProgram) {
  686. this._program = previousProgram;
  687. this._isReady = true;
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. }
  693. if (fallbacks && fallbacks.isMoreFallbacks) {
  694. BABYLON.Tools.Error("Trying next fallback.");
  695. this.defines = fallbacks.reduce(this.defines, this);
  696. this._prepareEffect();
  697. }
  698. else {
  699. if (this.onError) {
  700. this.onError(this, this._compilationError);
  701. }
  702. this.onErrorObservable.notifyObservers(this);
  703. this.onErrorObservable.clear();
  704. // Unbind mesh reference in fallbacks
  705. if (this._fallbacks) {
  706. this._fallbacks.unBindMesh();
  707. }
  708. }
  709. }
  710. };
  711. Object.defineProperty(Effect.prototype, "isSupported", {
  712. /**
  713. * Checks if the effect is supported. (Must be called after compilation)
  714. */
  715. get: function () {
  716. return this._compilationError === "";
  717. },
  718. enumerable: true,
  719. configurable: true
  720. });
  721. /**
  722. * Binds a texture to the engine to be used as output of the shader.
  723. * @param channel Name of the output variable.
  724. * @param texture Texture to bind.
  725. */
  726. Effect.prototype._bindTexture = function (channel, texture) {
  727. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  728. };
  729. /**
  730. * Sets a texture on the engine to be used in the shader.
  731. * @param channel Name of the sampler variable.
  732. * @param texture Texture to set.
  733. */
  734. Effect.prototype.setTexture = function (channel, texture) {
  735. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  736. };
  737. /**
  738. * Sets an array of textures on the engine to be used in the shader.
  739. * @param channel Name of the variable.
  740. * @param textures Textures to set.
  741. */
  742. Effect.prototype.setTextureArray = function (channel, textures) {
  743. if (this._samplers.indexOf(channel + "Ex") === -1) {
  744. var initialPos = this._samplers.indexOf(channel);
  745. for (var index = 1; index < textures.length; index++) {
  746. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  747. }
  748. }
  749. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  750. };
  751. /**
  752. * 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)
  753. * @param channel Name of the sampler variable.
  754. * @param postProcess Post process to get the input texture from.
  755. */
  756. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  757. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  758. };
  759. /** @ignore */
  760. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  761. var cache = this._valueCache[uniformName];
  762. var flag = matrix.updateFlag;
  763. if (cache !== undefined && cache === flag) {
  764. return false;
  765. }
  766. this._valueCache[uniformName] = flag;
  767. return true;
  768. };
  769. /** @ignore */
  770. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  771. var cache = this._valueCache[uniformName];
  772. if (!cache) {
  773. cache = [x, y];
  774. this._valueCache[uniformName] = cache;
  775. return true;
  776. }
  777. var changed = false;
  778. if (cache[0] !== x) {
  779. cache[0] = x;
  780. changed = true;
  781. }
  782. if (cache[1] !== y) {
  783. cache[1] = y;
  784. changed = true;
  785. }
  786. return changed;
  787. };
  788. /** @ignore */
  789. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  790. var cache = this._valueCache[uniformName];
  791. if (!cache) {
  792. cache = [x, y, z];
  793. this._valueCache[uniformName] = cache;
  794. return true;
  795. }
  796. var changed = false;
  797. if (cache[0] !== x) {
  798. cache[0] = x;
  799. changed = true;
  800. }
  801. if (cache[1] !== y) {
  802. cache[1] = y;
  803. changed = true;
  804. }
  805. if (cache[2] !== z) {
  806. cache[2] = z;
  807. changed = true;
  808. }
  809. return changed;
  810. };
  811. /** @ignore */
  812. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  813. var cache = this._valueCache[uniformName];
  814. if (!cache) {
  815. cache = [x, y, z, w];
  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. if (cache[2] !== z) {
  829. cache[2] = z;
  830. changed = true;
  831. }
  832. if (cache[3] !== w) {
  833. cache[3] = w;
  834. changed = true;
  835. }
  836. return changed;
  837. };
  838. /**
  839. * Binds a buffer to a uniform.
  840. * @param buffer Buffer to bind.
  841. * @param name Name of the uniform variable to bind to.
  842. */
  843. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  844. var bufferName = this._uniformBuffersNames[name];
  845. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  846. return;
  847. }
  848. Effect._baseCache[bufferName] = buffer;
  849. this._engine.bindUniformBufferBase(buffer, bufferName);
  850. };
  851. /**
  852. * Binds block to a uniform.
  853. * @param blockName Name of the block to bind.
  854. * @param index Index to bind.
  855. */
  856. Effect.prototype.bindUniformBlock = function (blockName, index) {
  857. this._engine.bindUniformBlock(this._program, blockName, index);
  858. };
  859. /**
  860. * Sets an interger value on a uniform variable.
  861. * @param uniformName Name of the variable.
  862. * @param value Value to be set.
  863. * @returns this effect.
  864. */
  865. Effect.prototype.setInt = function (uniformName, value) {
  866. var cache = this._valueCache[uniformName];
  867. if (cache !== undefined && cache === value)
  868. return this;
  869. this._valueCache[uniformName] = value;
  870. this._engine.setInt(this.getUniform(uniformName), value);
  871. return this;
  872. };
  873. /**
  874. * Sets an int array on a uniform variable.
  875. * @param uniformName Name of the variable.
  876. * @param array array to be set.
  877. * @returns this effect.
  878. */
  879. Effect.prototype.setIntArray = function (uniformName, array) {
  880. this._valueCache[uniformName] = null;
  881. this._engine.setIntArray(this.getUniform(uniformName), array);
  882. return this;
  883. };
  884. /**
  885. * 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)
  886. * @param uniformName Name of the variable.
  887. * @param array array to be set.
  888. * @returns this effect.
  889. */
  890. Effect.prototype.setIntArray2 = function (uniformName, array) {
  891. this._valueCache[uniformName] = null;
  892. this._engine.setIntArray2(this.getUniform(uniformName), array);
  893. return this;
  894. };
  895. /**
  896. * 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)
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray3 = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray3(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * 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)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray4 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray4(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an float array on a uniform variable.
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setFloatArray = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setFloatArray(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * 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)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * 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)
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * 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)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an array on a uniform variable.
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setArray = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setArray(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * 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)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setArray2 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setArray2(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * 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)
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray3 = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray3(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * 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)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray4 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray4(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets matrices on a uniform variable.
  1007. * @param uniformName Name of the variable.
  1008. * @param matrices matrices to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1012. if (!matrices) {
  1013. return this;
  1014. }
  1015. this._valueCache[uniformName] = null;
  1016. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1017. return this;
  1018. };
  1019. /**
  1020. * Sets matrix on a uniform variable.
  1021. * @param uniformName Name of the variable.
  1022. * @param matrix matrix to be set.
  1023. * @returns this effect.
  1024. */
  1025. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1026. if (this._cacheMatrix(uniformName, matrix)) {
  1027. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1028. }
  1029. return this;
  1030. };
  1031. /**
  1032. * 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)
  1033. * @param uniformName Name of the variable.
  1034. * @param matrix matrix to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1044. * @param uniformName Name of the variable.
  1045. * @param matrix matrix to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a float on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param value value to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat = function (uniformName, value) {
  1060. var cache = this._valueCache[uniformName];
  1061. if (cache !== undefined && cache === value)
  1062. return this;
  1063. this._valueCache[uniformName] = value;
  1064. this._engine.setFloat(this.getUniform(uniformName), value);
  1065. return this;
  1066. };
  1067. /**
  1068. * Sets a boolean on a uniform variable.
  1069. * @param uniformName Name of the variable.
  1070. * @param bool value to be set.
  1071. * @returns this effect.
  1072. */
  1073. Effect.prototype.setBool = function (uniformName, bool) {
  1074. var cache = this._valueCache[uniformName];
  1075. if (cache !== undefined && cache === bool)
  1076. return this;
  1077. this._valueCache[uniformName] = bool;
  1078. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1079. return this;
  1080. };
  1081. /**
  1082. * Sets a Vector2 on a uniform variable.
  1083. * @param uniformName Name of the variable.
  1084. * @param vector2 vector2 to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1088. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1089. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1090. }
  1091. return this;
  1092. };
  1093. /**
  1094. * Sets a float2 on a uniform variable.
  1095. * @param uniformName Name of the variable.
  1096. * @param x First float in float2.
  1097. * @param y Second float in float2.
  1098. * @returns this effect.
  1099. */
  1100. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1101. if (this._cacheFloat2(uniformName, x, y)) {
  1102. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1103. }
  1104. return this;
  1105. };
  1106. /**
  1107. * Sets a Vector3 on a uniform variable.
  1108. * @param uniformName Name of the variable.
  1109. * @param vector3 Value to be set.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1113. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1114. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a float3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param x First float in float3.
  1122. * @param y Second float in float3.
  1123. * @param z Third float in float3.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1127. if (this._cacheFloat3(uniformName, x, y, z)) {
  1128. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * Sets a Vector4 on a uniform variable.
  1134. * @param uniformName Name of the variable.
  1135. * @param vector4 Value to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1139. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1140. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1141. }
  1142. return this;
  1143. };
  1144. /**
  1145. * Sets a float4 on a uniform variable.
  1146. * @param uniformName Name of the variable.
  1147. * @param x First float in float4.
  1148. * @param y Second float in float4.
  1149. * @param z Third float in float4.
  1150. * @param w Fourth float in float4.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1154. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1155. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a Color3 on a uniform variable.
  1161. * @param uniformName Name of the variable.
  1162. * @param color3 Value to be set.
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setColor3 = function (uniformName, color3) {
  1166. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1167. this._engine.setColor3(this.getUniform(uniformName), color3);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a Color4 on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param color3 Value to be set.
  1175. * @param alpha Alpha value to be set.
  1176. * @returns this effect.
  1177. */
  1178. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1179. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1180. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1181. }
  1182. return this;
  1183. };
  1184. /**
  1185. * Sets a Color4 on a uniform variable
  1186. * @param uniformName defines the name of the variable
  1187. * @param color4 defines the value to be set
  1188. * @returns this effect.
  1189. */
  1190. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1191. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1192. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1193. }
  1194. return this;
  1195. };
  1196. /**
  1197. * Resets the cache of effects.
  1198. */
  1199. Effect.ResetCache = function () {
  1200. Effect._baseCache = {};
  1201. };
  1202. Effect._uniqueIdSeed = 0;
  1203. Effect._baseCache = {};
  1204. // Statics
  1205. /**
  1206. * Store of each shader (The can be looked up using effect.key)
  1207. */
  1208. Effect.ShadersStore = {};
  1209. /**
  1210. * Store of each included file for a shader (The can be looked up using effect.key)
  1211. */
  1212. Effect.IncludesShadersStore = {};
  1213. return Effect;
  1214. }());
  1215. BABYLON.Effect = Effect;
  1216. })(BABYLON || (BABYLON = {}));
  1217. //# sourceMappingURL=babylon.effect.js.map
  1218. //# sourceMappingURL=babylon.types.js.map
  1219. var BABYLON;
  1220. (function (BABYLON) {
  1221. var KeyboardEventTypes = /** @class */ (function () {
  1222. function KeyboardEventTypes() {
  1223. }
  1224. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1225. get: function () {
  1226. return KeyboardEventTypes._KEYDOWN;
  1227. },
  1228. enumerable: true,
  1229. configurable: true
  1230. });
  1231. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1232. get: function () {
  1233. return KeyboardEventTypes._KEYUP;
  1234. },
  1235. enumerable: true,
  1236. configurable: true
  1237. });
  1238. KeyboardEventTypes._KEYDOWN = 0x01;
  1239. KeyboardEventTypes._KEYUP = 0x02;
  1240. return KeyboardEventTypes;
  1241. }());
  1242. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1243. var KeyboardInfo = /** @class */ (function () {
  1244. function KeyboardInfo(type, event) {
  1245. this.type = type;
  1246. this.event = event;
  1247. }
  1248. return KeyboardInfo;
  1249. }());
  1250. BABYLON.KeyboardInfo = KeyboardInfo;
  1251. /**
  1252. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1253. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1254. */
  1255. var KeyboardInfoPre = /** @class */ (function (_super) {
  1256. __extends(KeyboardInfoPre, _super);
  1257. function KeyboardInfoPre(type, event) {
  1258. var _this = _super.call(this, type, event) || this;
  1259. _this.skipOnPointerObservable = false;
  1260. return _this;
  1261. }
  1262. return KeyboardInfoPre;
  1263. }(KeyboardInfo));
  1264. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1265. })(BABYLON || (BABYLON = {}));
  1266. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1267. var BABYLON;
  1268. (function (BABYLON) {
  1269. var PointerEventTypes = /** @class */ (function () {
  1270. function PointerEventTypes() {
  1271. }
  1272. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1273. get: function () {
  1274. return PointerEventTypes._POINTERDOWN;
  1275. },
  1276. enumerable: true,
  1277. configurable: true
  1278. });
  1279. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1280. get: function () {
  1281. return PointerEventTypes._POINTERUP;
  1282. },
  1283. enumerable: true,
  1284. configurable: true
  1285. });
  1286. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1287. get: function () {
  1288. return PointerEventTypes._POINTERMOVE;
  1289. },
  1290. enumerable: true,
  1291. configurable: true
  1292. });
  1293. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERWHEEL;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERPICK;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERTAP;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERDOUBLETAP;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. PointerEventTypes._POINTERDOWN = 0x01;
  1322. PointerEventTypes._POINTERUP = 0x02;
  1323. PointerEventTypes._POINTERMOVE = 0x04;
  1324. PointerEventTypes._POINTERWHEEL = 0x08;
  1325. PointerEventTypes._POINTERPICK = 0x10;
  1326. PointerEventTypes._POINTERTAP = 0x20;
  1327. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1328. return PointerEventTypes;
  1329. }());
  1330. BABYLON.PointerEventTypes = PointerEventTypes;
  1331. var PointerInfoBase = /** @class */ (function () {
  1332. function PointerInfoBase(type, event) {
  1333. this.type = type;
  1334. this.event = event;
  1335. }
  1336. return PointerInfoBase;
  1337. }());
  1338. BABYLON.PointerInfoBase = PointerInfoBase;
  1339. /**
  1340. * This class is used to store pointer related info for the onPrePointerObservable event.
  1341. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1342. */
  1343. var PointerInfoPre = /** @class */ (function (_super) {
  1344. __extends(PointerInfoPre, _super);
  1345. function PointerInfoPre(type, event, localX, localY) {
  1346. var _this = _super.call(this, type, event) || this;
  1347. _this.skipOnPointerObservable = false;
  1348. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1349. return _this;
  1350. }
  1351. return PointerInfoPre;
  1352. }(PointerInfoBase));
  1353. BABYLON.PointerInfoPre = PointerInfoPre;
  1354. /**
  1355. * This type contains all the data related to a pointer event in Babylon.js.
  1356. * 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.
  1357. */
  1358. var PointerInfo = /** @class */ (function (_super) {
  1359. __extends(PointerInfo, _super);
  1360. function PointerInfo(type, event, pickInfo) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.pickInfo = pickInfo;
  1363. return _this;
  1364. }
  1365. return PointerInfo;
  1366. }(PointerInfoBase));
  1367. BABYLON.PointerInfo = PointerInfo;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.pointerEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. BABYLON.ToGammaSpace = 1 / 2.2;
  1373. BABYLON.ToLinearSpace = 2.2;
  1374. BABYLON.Epsilon = 0.001;
  1375. /**
  1376. * Class used to hold a RBG color
  1377. */
  1378. var Color3 = /** @class */ (function () {
  1379. /**
  1380. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1381. * @param r defines the red component (between 0 and 1, default is 0)
  1382. * @param g defines the green component (between 0 and 1, default is 0)
  1383. * @param b defines the blue component (between 0 and 1, default is 0)
  1384. */
  1385. function Color3(
  1386. /**
  1387. * Defines the red component (between 0 and 1, default is 0)
  1388. */
  1389. r,
  1390. /**
  1391. * Defines the green component (between 0 and 1, default is 0)
  1392. */
  1393. g,
  1394. /**
  1395. * Defines the blue component (between 0 and 1, default is 0)
  1396. */
  1397. b) {
  1398. if (r === void 0) { r = 0; }
  1399. if (g === void 0) { g = 0; }
  1400. if (b === void 0) { b = 0; }
  1401. this.r = r;
  1402. this.g = g;
  1403. this.b = b;
  1404. }
  1405. /**
  1406. * Creates a string with the Color3 current values
  1407. * @returns the string representation of the Color3 object
  1408. */
  1409. Color3.prototype.toString = function () {
  1410. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1411. };
  1412. /**
  1413. * Returns the string "Color3"
  1414. * @returns "Color3"
  1415. */
  1416. Color3.prototype.getClassName = function () {
  1417. return "Color3";
  1418. };
  1419. /**
  1420. * Compute the Color3 hash code
  1421. * @returns an unique number that can be used to hash Color3 objects
  1422. */
  1423. Color3.prototype.getHashCode = function () {
  1424. var hash = this.r || 0;
  1425. hash = (hash * 397) ^ (this.g || 0);
  1426. hash = (hash * 397) ^ (this.b || 0);
  1427. return hash;
  1428. };
  1429. // Operators
  1430. /**
  1431. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1432. * @param array defines the array where to store the r,g,b components
  1433. * @param index defines an optional index in the target array to define where to start storing values
  1434. * @returns the current Color3 object
  1435. */
  1436. Color3.prototype.toArray = function (array, index) {
  1437. if (index === undefined) {
  1438. index = 0;
  1439. }
  1440. array[index] = this.r;
  1441. array[index + 1] = this.g;
  1442. array[index + 2] = this.b;
  1443. return this;
  1444. };
  1445. /**
  1446. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1447. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1448. * @returns a new {BABYLON.Color4} object
  1449. */
  1450. Color3.prototype.toColor4 = function (alpha) {
  1451. if (alpha === void 0) { alpha = 1; }
  1452. return new Color4(this.r, this.g, this.b, alpha);
  1453. };
  1454. /**
  1455. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1456. * @returns the new array
  1457. */
  1458. Color3.prototype.asArray = function () {
  1459. var result = new Array();
  1460. this.toArray(result, 0);
  1461. return result;
  1462. };
  1463. /**
  1464. * Returns the luminance value
  1465. * @returns a float value
  1466. */
  1467. Color3.prototype.toLuminance = function () {
  1468. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1469. };
  1470. /**
  1471. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1472. * @param otherColor defines the second operand
  1473. * @returns the new Color3 object
  1474. */
  1475. Color3.prototype.multiply = function (otherColor) {
  1476. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1477. };
  1478. /**
  1479. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1480. * @param otherColor defines the second operand
  1481. * @param result defines the Color3 object where to store the result
  1482. * @returns the current Color3
  1483. */
  1484. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1485. result.r = this.r * otherColor.r;
  1486. result.g = this.g * otherColor.g;
  1487. result.b = this.b * otherColor.b;
  1488. return this;
  1489. };
  1490. /**
  1491. * Determines equality between Color3 objects
  1492. * @param otherColor defines the second operand
  1493. * @returns true if the rgb values are equal to the passed ones
  1494. */
  1495. Color3.prototype.equals = function (otherColor) {
  1496. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1497. };
  1498. /**
  1499. * Determines equality between the current Color3 object and a set of r,b,g values
  1500. * @param r defines the red component to check
  1501. * @param g defines the green component to check
  1502. * @param b defines the blue component to check
  1503. * @returns true if the rgb values are equal to the passed ones
  1504. */
  1505. Color3.prototype.equalsFloats = function (r, g, b) {
  1506. return this.r === r && this.g === g && this.b === b;
  1507. };
  1508. /**
  1509. * Multiplies in place each rgb value by scale
  1510. * @param scale defines the scaling factor
  1511. * @returns the updated Color3.
  1512. */
  1513. Color3.prototype.scale = function (scale) {
  1514. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1515. };
  1516. /**
  1517. * Multiplies the rgb values by scale and stores the result into "result"
  1518. * @param scale defines the scaling factor
  1519. * @param result defines the Color3 object where to store the result
  1520. * @returns the unmodified current Color3.
  1521. */
  1522. Color3.prototype.scaleToRef = function (scale, result) {
  1523. result.r = this.r * scale;
  1524. result.g = this.g * scale;
  1525. result.b = this.b * scale;
  1526. return this;
  1527. };
  1528. /**
  1529. * Clamps the rgb values by the min and max values and stores the result into "result"
  1530. * @param min defines minimum clamping value (default is 0)
  1531. * @param max defines maximum clamping value (default is 1)
  1532. * @param result defines color to store the result into
  1533. * @returns the original Color3
  1534. */
  1535. Color3.prototype.clampToRef = function (min, max, result) {
  1536. if (min === void 0) { min = 0; }
  1537. if (max === void 0) { max = 1; }
  1538. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1539. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1540. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1541. return this;
  1542. };
  1543. /**
  1544. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1545. * @param otherColor defines the second operand
  1546. * @returns the new Color3
  1547. */
  1548. Color3.prototype.add = function (otherColor) {
  1549. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1550. };
  1551. /**
  1552. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1553. * @param otherColor defines the second operand
  1554. * @param result defines Color3 object to store the result into
  1555. * @returns the unmodified current Color3
  1556. */
  1557. Color3.prototype.addToRef = function (otherColor, result) {
  1558. result.r = this.r + otherColor.r;
  1559. result.g = this.g + otherColor.g;
  1560. result.b = this.b + otherColor.b;
  1561. return this;
  1562. };
  1563. /**
  1564. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1565. * @param otherColor defines the second operand
  1566. * @returns the new Color3
  1567. */
  1568. Color3.prototype.subtract = function (otherColor) {
  1569. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1570. };
  1571. /**
  1572. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1573. * @param otherColor defines the second operand
  1574. * @param result defines Color3 object to store the result into
  1575. * @returns the unmodified current Color3
  1576. */
  1577. Color3.prototype.subtractToRef = function (otherColor, result) {
  1578. result.r = this.r - otherColor.r;
  1579. result.g = this.g - otherColor.g;
  1580. result.b = this.b - otherColor.b;
  1581. return this;
  1582. };
  1583. /**
  1584. * Copy the current object
  1585. * @returns a new Color3 copied the current one
  1586. */
  1587. Color3.prototype.clone = function () {
  1588. return new Color3(this.r, this.g, this.b);
  1589. };
  1590. /**
  1591. * Copies the rgb values from the source in the current Color3
  1592. * @param source defines the source Color3 object
  1593. * @returns the updated Color3 object
  1594. */
  1595. Color3.prototype.copyFrom = function (source) {
  1596. this.r = source.r;
  1597. this.g = source.g;
  1598. this.b = source.b;
  1599. return this;
  1600. };
  1601. /**
  1602. * Updates the Color3 rgb values from the passed floats
  1603. * @param r defines the red component to read from
  1604. * @param g defines the green component to read from
  1605. * @param b defines the blue component to read from
  1606. * @returns the current Color3 object
  1607. */
  1608. Color3.prototype.copyFromFloats = function (r, g, b) {
  1609. this.r = r;
  1610. this.g = g;
  1611. this.b = b;
  1612. return this;
  1613. };
  1614. /**
  1615. * Updates the Color3 rgb values from the passed floats
  1616. * @param r defines the red component to read from
  1617. * @param g defines the green component to read from
  1618. * @param b defines the blue component to read from
  1619. * @returns the current Color3 object
  1620. */
  1621. Color3.prototype.set = function (r, g, b) {
  1622. return this.copyFromFloats(r, g, b);
  1623. };
  1624. /**
  1625. * Compute the Color3 hexadecimal code as a string
  1626. * @returns a string containing the hexadecimal representation of the Color3 object
  1627. */
  1628. Color3.prototype.toHexString = function () {
  1629. var intR = (this.r * 255) | 0;
  1630. var intG = (this.g * 255) | 0;
  1631. var intB = (this.b * 255) | 0;
  1632. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1633. };
  1634. /**
  1635. * Computes a new Color3 converted from the current one to linear space
  1636. * @returns a new Color3 object
  1637. */
  1638. Color3.prototype.toLinearSpace = function () {
  1639. var convertedColor = new Color3();
  1640. this.toLinearSpaceToRef(convertedColor);
  1641. return convertedColor;
  1642. };
  1643. /**
  1644. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1645. * @param convertedColor defines the Color3 object where to store the linear space version
  1646. * @returns the unmodified Color3
  1647. */
  1648. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1649. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1650. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1651. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1652. return this;
  1653. };
  1654. /**
  1655. * Computes a new Color3 converted from the current one to gamma space
  1656. * @returns a new Color3 object
  1657. */
  1658. Color3.prototype.toGammaSpace = function () {
  1659. var convertedColor = new Color3();
  1660. this.toGammaSpaceToRef(convertedColor);
  1661. return convertedColor;
  1662. };
  1663. /**
  1664. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1665. * @param convertedColor defines the Color3 object where to store the gamma space version
  1666. * @returns the unmodified Color3
  1667. */
  1668. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1669. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1670. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1671. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1672. return this;
  1673. };
  1674. // Statics
  1675. /**
  1676. * Creates a new Color3 from the string containing valid hexadecimal values
  1677. * @param hex defines a string containing valid hexadecimal values
  1678. * @returns a new Color3 object
  1679. */
  1680. Color3.FromHexString = function (hex) {
  1681. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1682. return new Color3(0, 0, 0);
  1683. }
  1684. var r = parseInt(hex.substring(1, 3), 16);
  1685. var g = parseInt(hex.substring(3, 5), 16);
  1686. var b = parseInt(hex.substring(5, 7), 16);
  1687. return Color3.FromInts(r, g, b);
  1688. };
  1689. /**
  1690. * Creates a new Vector3 from the starting index of the passed array
  1691. * @param array defines the source array
  1692. * @param offset defines an offset in the source array
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.FromArray = function (array, offset) {
  1696. if (offset === void 0) { offset = 0; }
  1697. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1698. };
  1699. /**
  1700. * Creates a new Color3 from integer values (< 256)
  1701. * @param r defines the red component to read from (value between 0 and 255)
  1702. * @param g defines the green component to read from (value between 0 and 255)
  1703. * @param b defines the blue component to read from (value between 0 and 255)
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.FromInts = function (r, g, b) {
  1707. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1708. };
  1709. /**
  1710. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1711. * @param start defines the start Color3 value
  1712. * @param end defines the end Color3 value
  1713. * @param amount defines the gradient value between start and end
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.Lerp = function (start, end, amount) {
  1717. var r = start.r + ((end.r - start.r) * amount);
  1718. var g = start.g + ((end.g - start.g) * amount);
  1719. var b = start.b + ((end.b - start.b) * amount);
  1720. return new Color3(r, g, b);
  1721. };
  1722. /**
  1723. * Returns a Color3 value containing a red color
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Red = function () { return new Color3(1, 0, 0); };
  1727. /**
  1728. * Returns a Color3 value containing a green color
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.Green = function () { return new Color3(0, 1, 0); };
  1732. /**
  1733. * Returns a Color3 value containing a blue color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1737. /**
  1738. * Returns a Color3 value containing a black color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Black = function () { return new Color3(0, 0, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a white color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.White = function () { return new Color3(1, 1, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a purple color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1752. /**
  1753. * Returns a Color3 value containing a magenta color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a yellow color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a gray color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1767. /**
  1768. * Returns a Color3 value containing a teal color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1772. /**
  1773. * Returns a Color3 value containing a random color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1777. return Color3;
  1778. }());
  1779. BABYLON.Color3 = Color3;
  1780. /**
  1781. * Class used to hold a RBGA color
  1782. */
  1783. var Color4 = /** @class */ (function () {
  1784. /**
  1785. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1786. * @param r defines the red component (between 0 and 1, default is 0)
  1787. * @param g defines the green component (between 0 and 1, default is 0)
  1788. * @param b defines the blue component (between 0 and 1, default is 0)
  1789. * @param a defines the alpha component (between 0 and 1, default is 1)
  1790. */
  1791. function Color4(
  1792. /**
  1793. * Defines the red component (between 0 and 1, default is 0)
  1794. */
  1795. r,
  1796. /**
  1797. * Defines the green component (between 0 and 1, default is 0)
  1798. */
  1799. g,
  1800. /**
  1801. * Defines the blue component (between 0 and 1, default is 0)
  1802. */
  1803. b,
  1804. /**
  1805. * Defines the alpha component (between 0 and 1, default is 1)
  1806. */
  1807. a) {
  1808. if (r === void 0) { r = 0; }
  1809. if (g === void 0) { g = 0; }
  1810. if (b === void 0) { b = 0; }
  1811. if (a === void 0) { a = 1; }
  1812. this.r = r;
  1813. this.g = g;
  1814. this.b = b;
  1815. this.a = a;
  1816. }
  1817. // Operators
  1818. /**
  1819. * Adds in place the passed Color4 values to the current Color4 object
  1820. * @param right defines the second operand
  1821. * @returns the current updated Color4 object
  1822. */
  1823. Color4.prototype.addInPlace = function (right) {
  1824. this.r += right.r;
  1825. this.g += right.g;
  1826. this.b += right.b;
  1827. this.a += right.a;
  1828. return this;
  1829. };
  1830. /**
  1831. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1832. * @returns the new array
  1833. */
  1834. Color4.prototype.asArray = function () {
  1835. var result = new Array();
  1836. this.toArray(result, 0);
  1837. return result;
  1838. };
  1839. /**
  1840. * Stores from the starting index in the passed array the Color4 successive values
  1841. * @param array defines the array where to store the r,g,b components
  1842. * @param index defines an optional index in the target array to define where to start storing values
  1843. * @returns the current Color4 object
  1844. */
  1845. Color4.prototype.toArray = function (array, index) {
  1846. if (index === undefined) {
  1847. index = 0;
  1848. }
  1849. array[index] = this.r;
  1850. array[index + 1] = this.g;
  1851. array[index + 2] = this.b;
  1852. array[index + 3] = this.a;
  1853. return this;
  1854. };
  1855. /**
  1856. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1857. * @param right defines the second operand
  1858. * @returns a new Color4 object
  1859. */
  1860. Color4.prototype.add = function (right) {
  1861. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.subtract = function (right) {
  1869. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1870. };
  1871. /**
  1872. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1873. * @param right defines the second operand
  1874. * @param result defines the Color4 object where to store the result
  1875. * @returns the current Color4 object
  1876. */
  1877. Color4.prototype.subtractToRef = function (right, result) {
  1878. result.r = this.r - right.r;
  1879. result.g = this.g - right.g;
  1880. result.b = this.b - right.b;
  1881. result.a = this.a - right.a;
  1882. return this;
  1883. };
  1884. /**
  1885. * Creates a new Color4 with the current Color4 values multiplied by scale
  1886. * @param scale defines the scaling factor to apply
  1887. * @returns a new Color4 object
  1888. */
  1889. Color4.prototype.scale = function (scale) {
  1890. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1891. };
  1892. /**
  1893. * Multiplies the current Color4 values by scale and stores the result in "result"
  1894. * @param scale defines the scaling factor to apply
  1895. * @param result defines the Color4 object where to store the result
  1896. * @returns the current Color4.
  1897. */
  1898. Color4.prototype.scaleToRef = function (scale, result) {
  1899. result.r = this.r * scale;
  1900. result.g = this.g * scale;
  1901. result.b = this.b * scale;
  1902. result.a = this.a * scale;
  1903. return this;
  1904. };
  1905. /**
  1906. * Clamps the rgb values by the min and max values and stores the result into "result"
  1907. * @param min defines minimum clamping value (default is 0)
  1908. * @param max defines maximum clamping value (default is 1)
  1909. * @param result defines color to store the result into.
  1910. * @returns the cuurent Color4
  1911. */
  1912. Color4.prototype.clampToRef = function (min, max, result) {
  1913. if (min === void 0) { min = 0; }
  1914. if (max === void 0) { max = 1; }
  1915. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1916. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1917. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1918. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1919. return this;
  1920. };
  1921. /**
  1922. * Multipy an Color4 value by another and return a new Color4 object
  1923. * @param color defines the Color4 value to multiply by
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.multiply = function (color) {
  1927. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1928. };
  1929. /**
  1930. * Multipy a Color4 value by another and push the result in a reference value
  1931. * @param color defines the Color4 value to multiply by
  1932. * @param result defines the Color4 to fill the result in
  1933. * @returns the result Color4
  1934. */
  1935. Color4.prototype.multiplyToRef = function (color, result) {
  1936. result.r = this.r * color.r;
  1937. result.g = this.g * color.g;
  1938. result.b = this.b * color.b;
  1939. result.a = this.a * color.a;
  1940. return result;
  1941. };
  1942. /**
  1943. * Creates a string with the Color4 current values
  1944. * @returns the string representation of the Color4 object
  1945. */
  1946. Color4.prototype.toString = function () {
  1947. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1948. };
  1949. /**
  1950. * Returns the string "Color4"
  1951. * @returns "Color4"
  1952. */
  1953. Color4.prototype.getClassName = function () {
  1954. return "Color4";
  1955. };
  1956. /**
  1957. * Compute the Color4 hash code
  1958. * @returns an unique number that can be used to hash Color4 objects
  1959. */
  1960. Color4.prototype.getHashCode = function () {
  1961. var hash = this.r || 0;
  1962. hash = (hash * 397) ^ (this.g || 0);
  1963. hash = (hash * 397) ^ (this.b || 0);
  1964. hash = (hash * 397) ^ (this.a || 0);
  1965. return hash;
  1966. };
  1967. /**
  1968. * Creates a new Color4 copied from the current one
  1969. * @returns a new Color4 object
  1970. */
  1971. Color4.prototype.clone = function () {
  1972. return new Color4(this.r, this.g, this.b, this.a);
  1973. };
  1974. /**
  1975. * Copies the passed Color4 values into the current one
  1976. * @param source defines the source Color4 object
  1977. * @returns the current updated Color4 object
  1978. */
  1979. Color4.prototype.copyFrom = function (source) {
  1980. this.r = source.r;
  1981. this.g = source.g;
  1982. this.b = source.b;
  1983. this.a = source.a;
  1984. return this;
  1985. };
  1986. /**
  1987. * Copies the passed float values into the current one
  1988. * @param r defines the red component to read from
  1989. * @param g defines the green component to read from
  1990. * @param b defines the blue component to read from
  1991. * @param a defines the alpha component to read from
  1992. * @returns the current updated Color4 object
  1993. */
  1994. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1995. this.r = r;
  1996. this.g = g;
  1997. this.b = b;
  1998. this.a = a;
  1999. return this;
  2000. };
  2001. /**
  2002. * Copies the passed float values into the current one
  2003. * @param r defines the red component to read from
  2004. * @param g defines the green component to read from
  2005. * @param b defines the blue component to read from
  2006. * @param a defines the alpha component to read from
  2007. * @returns the current updated Color4 object
  2008. */
  2009. Color4.prototype.set = function (r, g, b, a) {
  2010. return this.copyFromFloats(r, g, b, a);
  2011. };
  2012. /**
  2013. * Compute the Color4 hexadecimal code as a string
  2014. * @returns a string containing the hexadecimal representation of the Color4 object
  2015. */
  2016. Color4.prototype.toHexString = function () {
  2017. var intR = (this.r * 255) | 0;
  2018. var intG = (this.g * 255) | 0;
  2019. var intB = (this.b * 255) | 0;
  2020. var intA = (this.a * 255) | 0;
  2021. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2022. };
  2023. /**
  2024. * Computes a new Color4 converted from the current one to linear space
  2025. * @returns a new Color4 object
  2026. */
  2027. Color4.prototype.toLinearSpace = function () {
  2028. var convertedColor = new Color4();
  2029. this.toLinearSpaceToRef(convertedColor);
  2030. return convertedColor;
  2031. };
  2032. /**
  2033. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2034. * @param convertedColor defines the Color4 object where to store the linear space version
  2035. * @returns the unmodified Color4
  2036. */
  2037. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2038. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2039. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2040. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2041. convertedColor.a = this.a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to gamma space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toGammaSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toGammaSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the gamma space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. // Statics
  2066. /**
  2067. * Creates a new Color4 from the string containing valid hexadecimal values
  2068. * @param hex defines a string containing valid hexadecimal values
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.FromHexString = function (hex) {
  2072. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2073. return new Color4(0.0, 0.0, 0.0, 0.0);
  2074. }
  2075. var r = parseInt(hex.substring(1, 3), 16);
  2076. var g = parseInt(hex.substring(3, 5), 16);
  2077. var b = parseInt(hex.substring(5, 7), 16);
  2078. var a = parseInt(hex.substring(7, 9), 16);
  2079. return Color4.FromInts(r, g, b, a);
  2080. };
  2081. /**
  2082. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2083. * @param left defines the start value
  2084. * @param right defines the end value
  2085. * @param amount defines the gradient factor
  2086. * @returns a new Color4 object
  2087. */
  2088. Color4.Lerp = function (left, right, amount) {
  2089. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2090. Color4.LerpToRef(left, right, amount, result);
  2091. return result;
  2092. };
  2093. /**
  2094. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2095. * @param left defines the start value
  2096. * @param right defines the end value
  2097. * @param amount defines the gradient factor
  2098. * @param result defines the Color4 object where to store data
  2099. */
  2100. Color4.LerpToRef = function (left, right, amount, result) {
  2101. result.r = left.r + (right.r - left.r) * amount;
  2102. result.g = left.g + (right.g - left.g) * amount;
  2103. result.b = left.b + (right.b - left.b) * amount;
  2104. result.a = left.a + (right.a - left.a) * amount;
  2105. };
  2106. /**
  2107. * Creates a new Color4 from the starting index element of the passed array
  2108. * @param array defines the source array to read from
  2109. * @param offset defines the offset in the source array
  2110. * @returns a new Color4 object
  2111. */
  2112. Color4.FromArray = function (array, offset) {
  2113. if (offset === void 0) { offset = 0; }
  2114. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2115. };
  2116. /**
  2117. * Creates a new Color3 from integer values (< 256)
  2118. * @param r defines the red component to read from (value between 0 and 255)
  2119. * @param g defines the green component to read from (value between 0 and 255)
  2120. * @param b defines the blue component to read from (value between 0 and 255)
  2121. * @param a defines the alpha component to read from (value between 0 and 255)
  2122. * @returns a new Color3 object
  2123. */
  2124. Color4.FromInts = function (r, g, b, a) {
  2125. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2126. };
  2127. /**
  2128. * Check the content of a given array and convert it to an array containing RGBA data
  2129. * If the original array was already containing count * 4 values then it is returned directly
  2130. * @param colors defines the array to check
  2131. * @param count defines the number of RGBA data to expect
  2132. * @returns an array containing count * 4 values (RGBA)
  2133. */
  2134. Color4.CheckColors4 = function (colors, count) {
  2135. // Check if color3 was used
  2136. if (colors.length === count * 3) {
  2137. var colors4 = [];
  2138. for (var index = 0; index < colors.length; index += 3) {
  2139. var newIndex = (index / 3) * 4;
  2140. colors4[newIndex] = colors[index];
  2141. colors4[newIndex + 1] = colors[index + 1];
  2142. colors4[newIndex + 2] = colors[index + 2];
  2143. colors4[newIndex + 3] = 1.0;
  2144. }
  2145. return colors4;
  2146. }
  2147. return colors;
  2148. };
  2149. return Color4;
  2150. }());
  2151. BABYLON.Color4 = Color4;
  2152. var Vector2 = /** @class */ (function () {
  2153. /**
  2154. * Creates a new Vector2 from the passed x and y coordinates.
  2155. */
  2156. function Vector2(x, y) {
  2157. this.x = x;
  2158. this.y = y;
  2159. }
  2160. /**
  2161. * Returns a string with the Vector2 coordinates.
  2162. */
  2163. Vector2.prototype.toString = function () {
  2164. return "{X: " + this.x + " Y:" + this.y + "}";
  2165. };
  2166. /**
  2167. * Returns the string "Vector2"
  2168. */
  2169. Vector2.prototype.getClassName = function () {
  2170. return "Vector2";
  2171. };
  2172. /**
  2173. * Returns the Vector2 hash code as a number.
  2174. */
  2175. Vector2.prototype.getHashCode = function () {
  2176. var hash = this.x || 0;
  2177. hash = (hash * 397) ^ (this.y || 0);
  2178. return hash;
  2179. };
  2180. // Operators
  2181. /**
  2182. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2183. * Returns the Vector2.
  2184. */
  2185. Vector2.prototype.toArray = function (array, index) {
  2186. if (index === void 0) { index = 0; }
  2187. array[index] = this.x;
  2188. array[index + 1] = this.y;
  2189. return this;
  2190. };
  2191. /**
  2192. * Returns a new array with 2 elements : the Vector2 coordinates.
  2193. */
  2194. Vector2.prototype.asArray = function () {
  2195. var result = new Array();
  2196. this.toArray(result, 0);
  2197. return result;
  2198. };
  2199. /**
  2200. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2201. * Returns the updated Vector2.
  2202. */
  2203. Vector2.prototype.copyFrom = function (source) {
  2204. this.x = source.x;
  2205. this.y = source.y;
  2206. return this;
  2207. };
  2208. /**
  2209. * Sets the Vector2 coordinates with the passed floats.
  2210. * Returns the updated Vector2.
  2211. */
  2212. Vector2.prototype.copyFromFloats = function (x, y) {
  2213. this.x = x;
  2214. this.y = y;
  2215. return this;
  2216. };
  2217. /**
  2218. * Sets the Vector2 coordinates with the passed floats.
  2219. * Returns the updated Vector2.
  2220. */
  2221. Vector2.prototype.set = function (x, y) {
  2222. return this.copyFromFloats(x, y);
  2223. };
  2224. /**
  2225. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2226. */
  2227. Vector2.prototype.add = function (otherVector) {
  2228. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2229. };
  2230. /**
  2231. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2232. * Returns the Vector2.
  2233. */
  2234. Vector2.prototype.addToRef = function (otherVector, result) {
  2235. result.x = this.x + otherVector.x;
  2236. result.y = this.y + otherVector.y;
  2237. return this;
  2238. };
  2239. /**
  2240. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2241. * Returns the updated Vector2.
  2242. */
  2243. Vector2.prototype.addInPlace = function (otherVector) {
  2244. this.x += otherVector.x;
  2245. this.y += otherVector.y;
  2246. return this;
  2247. };
  2248. /**
  2249. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2250. */
  2251. Vector2.prototype.addVector3 = function (otherVector) {
  2252. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2253. };
  2254. /**
  2255. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2256. */
  2257. Vector2.prototype.subtract = function (otherVector) {
  2258. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2259. };
  2260. /**
  2261. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2262. * Returns the Vector2.
  2263. */
  2264. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2265. result.x = this.x - otherVector.x;
  2266. result.y = this.y - otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2271. * Returns the updated Vector2.
  2272. */
  2273. Vector2.prototype.subtractInPlace = function (otherVector) {
  2274. this.x -= otherVector.x;
  2275. this.y -= otherVector.y;
  2276. return this;
  2277. };
  2278. /**
  2279. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2280. * Returns the updated Vector2.
  2281. */
  2282. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2283. this.x *= otherVector.x;
  2284. this.y *= otherVector.y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2289. */
  2290. Vector2.prototype.multiply = function (otherVector) {
  2291. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2292. };
  2293. /**
  2294. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2295. * Returns the Vector2.
  2296. */
  2297. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2298. result.x = this.x * otherVector.x;
  2299. result.y = this.y * otherVector.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2304. */
  2305. Vector2.prototype.multiplyByFloats = function (x, y) {
  2306. return new Vector2(this.x * x, this.y * y);
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2310. */
  2311. Vector2.prototype.divide = function (otherVector) {
  2312. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.divideToRef = function (otherVector, result) {
  2319. result.x = this.x / otherVector.x;
  2320. result.y = this.y / otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Divides the current Vector3 coordinates by the passed ones.
  2325. * Returns the updated Vector3.
  2326. */
  2327. Vector2.prototype.divideInPlace = function (otherVector) {
  2328. return this.divideToRef(otherVector, this);
  2329. };
  2330. /**
  2331. * Returns a new Vector2 with current Vector2 negated coordinates.
  2332. */
  2333. Vector2.prototype.negate = function () {
  2334. return new Vector2(-this.x, -this.y);
  2335. };
  2336. /**
  2337. * Multiply the Vector2 coordinates by scale.
  2338. * Returns the updated Vector2.
  2339. */
  2340. Vector2.prototype.scaleInPlace = function (scale) {
  2341. this.x *= scale;
  2342. this.y *= scale;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2347. */
  2348. Vector2.prototype.scale = function (scale) {
  2349. return new Vector2(this.x * scale, this.y * scale);
  2350. };
  2351. /**
  2352. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2353. */
  2354. Vector2.prototype.equals = function (otherVector) {
  2355. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2356. };
  2357. /**
  2358. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2359. */
  2360. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2361. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2362. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2363. };
  2364. // Properties
  2365. /**
  2366. * Returns the vector length (float).
  2367. */
  2368. Vector2.prototype.length = function () {
  2369. return Math.sqrt(this.x * this.x + this.y * this.y);
  2370. };
  2371. /**
  2372. * Returns the vector squared length (float);
  2373. */
  2374. Vector2.prototype.lengthSquared = function () {
  2375. return (this.x * this.x + this.y * this.y);
  2376. };
  2377. // Methods
  2378. /**
  2379. * Normalize the vector.
  2380. * Returns the updated Vector2.
  2381. */
  2382. Vector2.prototype.normalize = function () {
  2383. var len = this.length();
  2384. if (len === 0)
  2385. return this;
  2386. var num = 1.0 / len;
  2387. this.x *= num;
  2388. this.y *= num;
  2389. return this;
  2390. };
  2391. /**
  2392. * Returns a new Vector2 copied from the Vector2.
  2393. */
  2394. Vector2.prototype.clone = function () {
  2395. return new Vector2(this.x, this.y);
  2396. };
  2397. // Statics
  2398. /**
  2399. * Returns a new Vector2(0, 0)
  2400. */
  2401. Vector2.Zero = function () {
  2402. return new Vector2(0, 0);
  2403. };
  2404. /**
  2405. * Returns a new Vector2(1, 1)
  2406. */
  2407. Vector2.One = function () {
  2408. return new Vector2(1, 1);
  2409. };
  2410. /**
  2411. * Returns a new Vector2 set from the passed index element of the passed array.
  2412. */
  2413. Vector2.FromArray = function (array, offset) {
  2414. if (offset === void 0) { offset = 0; }
  2415. return new Vector2(array[offset], array[offset + 1]);
  2416. };
  2417. /**
  2418. * Sets "result" from the passed index element of the passed array.
  2419. */
  2420. Vector2.FromArrayToRef = function (array, offset, result) {
  2421. result.x = array[offset];
  2422. result.y = array[offset + 1];
  2423. };
  2424. /**
  2425. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2426. */
  2427. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2428. var squared = amount * amount;
  2429. var cubed = amount * squared;
  2430. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2431. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2432. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2433. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2434. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2435. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2436. return new Vector2(x, y);
  2437. };
  2438. /**
  2439. * 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".
  2440. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2441. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2442. */
  2443. Vector2.Clamp = function (value, min, max) {
  2444. var x = value.x;
  2445. x = (x > max.x) ? max.x : x;
  2446. x = (x < min.x) ? min.x : x;
  2447. var y = value.y;
  2448. y = (y > max.y) ? max.y : y;
  2449. y = (y < min.y) ? min.y : y;
  2450. return new Vector2(x, y);
  2451. };
  2452. /**
  2453. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2454. */
  2455. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2456. var squared = amount * amount;
  2457. var cubed = amount * squared;
  2458. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2459. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2460. var part3 = (cubed - (2.0 * squared)) + amount;
  2461. var part4 = cubed - squared;
  2462. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2463. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2464. return new Vector2(x, y);
  2465. };
  2466. /**
  2467. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2468. */
  2469. Vector2.Lerp = function (start, end, amount) {
  2470. var x = start.x + ((end.x - start.x) * amount);
  2471. var y = start.y + ((end.y - start.y) * amount);
  2472. return new Vector2(x, y);
  2473. };
  2474. /**
  2475. * Returns the dot product (float) of the vector "left" and the vector "right".
  2476. */
  2477. Vector2.Dot = function (left, right) {
  2478. return left.x * right.x + left.y * right.y;
  2479. };
  2480. /**
  2481. * Returns a new Vector2 equal to the normalized passed vector.
  2482. */
  2483. Vector2.Normalize = function (vector) {
  2484. var newVector = vector.clone();
  2485. newVector.normalize();
  2486. return newVector;
  2487. };
  2488. /**
  2489. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2490. */
  2491. Vector2.Minimize = function (left, right) {
  2492. var x = (left.x < right.x) ? left.x : right.x;
  2493. var y = (left.y < right.y) ? left.y : right.y;
  2494. return new Vector2(x, y);
  2495. };
  2496. /**
  2497. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2498. */
  2499. Vector2.Maximize = function (left, right) {
  2500. var x = (left.x > right.x) ? left.x : right.x;
  2501. var y = (left.y > right.y) ? left.y : right.y;
  2502. return new Vector2(x, y);
  2503. };
  2504. /**
  2505. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2506. */
  2507. Vector2.Transform = function (vector, transformation) {
  2508. var r = Vector2.Zero();
  2509. Vector2.TransformToRef(vector, transformation, r);
  2510. return r;
  2511. };
  2512. /**
  2513. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2514. */
  2515. Vector2.TransformToRef = function (vector, transformation, result) {
  2516. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2517. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2518. result.x = x;
  2519. result.y = y;
  2520. };
  2521. /**
  2522. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2523. */
  2524. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2525. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2526. var sign = a < 0 ? -1 : 1;
  2527. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2528. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2529. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2530. };
  2531. /**
  2532. * Returns the distance (float) between the vectors "value1" and "value2".
  2533. */
  2534. Vector2.Distance = function (value1, value2) {
  2535. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2536. };
  2537. /**
  2538. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2539. */
  2540. Vector2.DistanceSquared = function (value1, value2) {
  2541. var x = value1.x - value2.x;
  2542. var y = value1.y - value2.y;
  2543. return (x * x) + (y * y);
  2544. };
  2545. /**
  2546. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2547. */
  2548. Vector2.Center = function (value1, value2) {
  2549. var center = value1.add(value2);
  2550. center.scaleInPlace(0.5);
  2551. return center;
  2552. };
  2553. /**
  2554. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2555. */
  2556. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2557. var l2 = Vector2.DistanceSquared(segA, segB);
  2558. if (l2 === 0.0) {
  2559. return Vector2.Distance(p, segA);
  2560. }
  2561. var v = segB.subtract(segA);
  2562. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2563. var proj = segA.add(v.multiplyByFloats(t, t));
  2564. return Vector2.Distance(p, proj);
  2565. };
  2566. return Vector2;
  2567. }());
  2568. BABYLON.Vector2 = Vector2;
  2569. /**
  2570. * Classed used to store (x,y,z) vector representation
  2571. * A Vector3 is the main object used in 3D geometry
  2572. * It can represent etiher the coordinates of a point the space, either a direction
  2573. * Reminder: Babylon.js uses a left handed forward facing system
  2574. */
  2575. var Vector3 = /** @class */ (function () {
  2576. /**
  2577. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2578. * @param x defines the first coordinates (on X axis)
  2579. * @param y defines the second coordinates (on Y axis)
  2580. * @param z defines the third coordinates (on Z axis)
  2581. */
  2582. function Vector3(
  2583. /**
  2584. * Defines the first coordinates (on X axis)
  2585. */
  2586. x,
  2587. /**
  2588. * Defines the second coordinates (on Y axis)
  2589. */
  2590. y,
  2591. /**
  2592. * Defines the third coordinates (on Z axis)
  2593. */
  2594. z) {
  2595. this.x = x;
  2596. this.y = y;
  2597. this.z = z;
  2598. }
  2599. /**
  2600. * Creates a string representation of the Vector3
  2601. * @returns a string with the Vector3 coordinates.
  2602. */
  2603. Vector3.prototype.toString = function () {
  2604. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2605. };
  2606. /**
  2607. * Gets the class name
  2608. * @returns the string "Vector3"
  2609. */
  2610. Vector3.prototype.getClassName = function () {
  2611. return "Vector3";
  2612. };
  2613. /**
  2614. * Creates the Vector3 hash code
  2615. * @returns a number which tends to be unique between Vector3 instances
  2616. */
  2617. Vector3.prototype.getHashCode = function () {
  2618. var hash = this.x || 0;
  2619. hash = (hash * 397) ^ (this.y || 0);
  2620. hash = (hash * 397) ^ (this.z || 0);
  2621. return hash;
  2622. };
  2623. // Operators
  2624. /**
  2625. * Creates an array containing three elements : the coordinates of the Vector3
  2626. * @returns a new array of numbers
  2627. */
  2628. Vector3.prototype.asArray = function () {
  2629. var result = [];
  2630. this.toArray(result, 0);
  2631. return result;
  2632. };
  2633. /**
  2634. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2635. * @param array defines the destination array
  2636. * @param index defines the offset in the destination array
  2637. * @returns the current Vector3
  2638. */
  2639. Vector3.prototype.toArray = function (array, index) {
  2640. if (index === void 0) { index = 0; }
  2641. array[index] = this.x;
  2642. array[index + 1] = this.y;
  2643. array[index + 2] = this.z;
  2644. return this;
  2645. };
  2646. /**
  2647. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2648. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2649. */
  2650. Vector3.prototype.toQuaternion = function () {
  2651. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2652. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2653. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2654. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2655. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2656. var cosy = Math.cos(this.y * 0.5);
  2657. var siny = Math.sin(this.y * 0.5);
  2658. result.x = coszMinusx * siny;
  2659. result.y = -sinzMinusx * siny;
  2660. result.z = sinxPlusz * cosy;
  2661. result.w = cosxPlusz * cosy;
  2662. return result;
  2663. };
  2664. /**
  2665. * Adds the passed vector to the current Vector3
  2666. * @param otherVector defines the second operand
  2667. * @returns the current updated Vector3
  2668. */
  2669. Vector3.prototype.addInPlace = function (otherVector) {
  2670. this.x += otherVector.x;
  2671. this.y += otherVector.y;
  2672. this.z += otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2677. * @param otherVector defines the second operand
  2678. * @returns the resulting Vector3
  2679. */
  2680. Vector3.prototype.add = function (otherVector) {
  2681. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2682. };
  2683. /**
  2684. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2685. * @param otherVector defines the second operand
  2686. * @param result defines the Vector3 object where to store the result
  2687. * @returns the current Vector3
  2688. */
  2689. Vector3.prototype.addToRef = function (otherVector, result) {
  2690. result.x = this.x + otherVector.x;
  2691. result.y = this.y + otherVector.y;
  2692. result.z = this.z + otherVector.z;
  2693. return this;
  2694. };
  2695. /**
  2696. * Subtract the passed vector from the current Vector3
  2697. * @param otherVector defines the second operand
  2698. * @returns the current updated Vector3
  2699. */
  2700. Vector3.prototype.subtractInPlace = function (otherVector) {
  2701. this.x -= otherVector.x;
  2702. this.y -= otherVector.y;
  2703. this.z -= otherVector.z;
  2704. return this;
  2705. };
  2706. /**
  2707. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2708. * @param otherVector defines the second operand
  2709. * @returns the resulting Vector3
  2710. */
  2711. Vector3.prototype.subtract = function (otherVector) {
  2712. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2713. };
  2714. /**
  2715. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2716. * @param otherVector defines the second operand
  2717. * @param result defines the Vector3 object where to store the result
  2718. * @returns the current Vector3
  2719. */
  2720. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2721. result.x = this.x - otherVector.x;
  2722. result.y = this.y - otherVector.y;
  2723. result.z = this.z - otherVector.z;
  2724. return this;
  2725. };
  2726. /**
  2727. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2728. * @param x defines the x coordinate of the operand
  2729. * @param y defines the y coordinate of the operand
  2730. * @param z defines the z coordinate of the operand
  2731. * @returns the resulting Vector3
  2732. */
  2733. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2734. return new Vector3(this.x - x, this.y - y, this.z - z);
  2735. };
  2736. /**
  2737. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2738. * @param x defines the x coordinate of the operand
  2739. * @param y defines the y coordinate of the operand
  2740. * @param z defines the z coordinate of the operand
  2741. * @param result defines the Vector3 object where to store the result
  2742. * @returns the current Vector3
  2743. */
  2744. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2745. result.x = this.x - x;
  2746. result.y = this.y - y;
  2747. result.z = this.z - z;
  2748. return this;
  2749. };
  2750. /**
  2751. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2752. * @returns a new Vector3
  2753. */
  2754. Vector3.prototype.negate = function () {
  2755. return new Vector3(-this.x, -this.y, -this.z);
  2756. };
  2757. /**
  2758. * Multiplies the Vector3 coordinates by the float "scale"
  2759. * @param scale defines the multiplier factor
  2760. * @returns the current updated Vector3
  2761. */
  2762. Vector3.prototype.scaleInPlace = function (scale) {
  2763. this.x *= scale;
  2764. this.y *= scale;
  2765. this.z *= scale;
  2766. return this;
  2767. };
  2768. /**
  2769. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2770. * @param scale defines the multiplier factor
  2771. * @returns a new Vector3
  2772. */
  2773. Vector3.prototype.scale = function (scale) {
  2774. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2775. };
  2776. /**
  2777. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2778. * @param scale defines the multiplier factor
  2779. * @param result defines the Vector3 object where to store the result
  2780. * @returns the current Vector3
  2781. */
  2782. Vector3.prototype.scaleToRef = function (scale, result) {
  2783. result.x = this.x * scale;
  2784. result.y = this.y * scale;
  2785. result.z = this.z * scale;
  2786. return this;
  2787. };
  2788. /**
  2789. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2790. * @param otherVector defines the second operand
  2791. * @returns true if both vectors are equals
  2792. */
  2793. Vector3.prototype.equals = function (otherVector) {
  2794. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2795. };
  2796. /**
  2797. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2798. * @param otherVector defines the second operand
  2799. * @param epsilon defines the minimal distance to define values as equals
  2800. * @returns true if both vectors are distant less than epsilon
  2801. */
  2802. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2803. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2804. 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);
  2805. };
  2806. /**
  2807. * Returns true if the current Vector3 coordinates equals the passed floats
  2808. * @param x defines the x coordinate of the operand
  2809. * @param y defines the y coordinate of the operand
  2810. * @param z defines the z coordinate of the operand
  2811. * @returns true if both vectors are equals
  2812. */
  2813. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2814. return this.x === x && this.y === y && this.z === z;
  2815. };
  2816. /**
  2817. * Multiplies the current Vector3 coordinates by the passed ones
  2818. * @param otherVector defines the second operand
  2819. * @returns the current updated Vector3
  2820. */
  2821. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2822. this.x *= otherVector.x;
  2823. this.y *= otherVector.y;
  2824. this.z *= otherVector.z;
  2825. return this;
  2826. };
  2827. /**
  2828. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2829. * @param otherVector defines the second operand
  2830. * @returns the new Vector3
  2831. */
  2832. Vector3.prototype.multiply = function (otherVector) {
  2833. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2834. };
  2835. /**
  2836. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2837. * @param otherVector defines the second operand
  2838. * @param result defines the Vector3 object where to store the result
  2839. * @returns the current Vector3
  2840. */
  2841. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2842. result.x = this.x * otherVector.x;
  2843. result.y = this.y * otherVector.y;
  2844. result.z = this.z * otherVector.z;
  2845. return this;
  2846. };
  2847. /**
  2848. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2849. * @param x defines the x coordinate of the operand
  2850. * @param y defines the y coordinate of the operand
  2851. * @param z defines the z coordinate of the operand
  2852. * @returns the new Vector3
  2853. */
  2854. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2855. return new Vector3(this.x * x, this.y * y, this.z * z);
  2856. };
  2857. /**
  2858. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2859. * @param otherVector defines the second operand
  2860. * @returns the new Vector3
  2861. */
  2862. Vector3.prototype.divide = function (otherVector) {
  2863. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2864. };
  2865. /**
  2866. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2867. * @param otherVector defines the second operand
  2868. * @param result defines the Vector3 object where to store the result
  2869. * @returns the current Vector3
  2870. */
  2871. Vector3.prototype.divideToRef = function (otherVector, result) {
  2872. result.x = this.x / otherVector.x;
  2873. result.y = this.y / otherVector.y;
  2874. result.z = this.z / otherVector.z;
  2875. return this;
  2876. };
  2877. /**
  2878. * Divides the current Vector3 coordinates by the passed ones.
  2879. * @param otherVector defines the second operand
  2880. * @returns the current updated Vector3
  2881. */
  2882. Vector3.prototype.divideInPlace = function (otherVector) {
  2883. return this.divideToRef(otherVector, this);
  2884. };
  2885. /**
  2886. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2887. * @param other defines the second operand
  2888. * @returns the current updated Vector3
  2889. */
  2890. Vector3.prototype.minimizeInPlace = function (other) {
  2891. if (other.x < this.x)
  2892. this.x = other.x;
  2893. if (other.y < this.y)
  2894. this.y = other.y;
  2895. if (other.z < this.z)
  2896. this.z = other.z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2901. * @param other defines the second operand
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.maximizeInPlace = function (other) {
  2905. if (other.x > this.x)
  2906. this.x = other.x;
  2907. if (other.y > this.y)
  2908. this.y = other.y;
  2909. if (other.z > this.z)
  2910. this.z = other.z;
  2911. return this;
  2912. };
  2913. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2914. /**
  2915. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2916. */
  2917. get: function () {
  2918. var absX = Math.abs(this.x);
  2919. var absY = Math.abs(this.y);
  2920. if (absX !== absY) {
  2921. return true;
  2922. }
  2923. var absZ = Math.abs(this.z);
  2924. if (absX !== absZ) {
  2925. return true;
  2926. }
  2927. if (absY !== absZ) {
  2928. return true;
  2929. }
  2930. return false;
  2931. },
  2932. enumerable: true,
  2933. configurable: true
  2934. });
  2935. // Properties
  2936. /**
  2937. * Gets the length of the Vector3
  2938. * @returns the length of the Vecto3
  2939. */
  2940. Vector3.prototype.length = function () {
  2941. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2942. };
  2943. /**
  2944. * Gets the squared length of the Vector3
  2945. * @returns squared length of the Vector3
  2946. */
  2947. Vector3.prototype.lengthSquared = function () {
  2948. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2949. };
  2950. /**
  2951. * Normalize the current Vector3.
  2952. * Please note that this is an in place operation.
  2953. * @returns the current updated Vector3
  2954. */
  2955. Vector3.prototype.normalize = function () {
  2956. var len = this.length();
  2957. if (len === 0 || len === 1.0)
  2958. return this;
  2959. var num = 1.0 / len;
  2960. this.x *= num;
  2961. this.y *= num;
  2962. this.z *= num;
  2963. return this;
  2964. };
  2965. /**
  2966. * Normalize the current Vector3 to a new vector
  2967. * @returns the new Vector3
  2968. */
  2969. Vector3.prototype.normalizeToNew = function () {
  2970. var normalized = new Vector3(0, 0, 0);
  2971. this.normalizeToRef(normalized);
  2972. return normalized;
  2973. };
  2974. /**
  2975. * Normalize the current Vector3 to the reference
  2976. * @param reference define the Vector3 to update
  2977. * @returns the updated Vector3
  2978. */
  2979. Vector3.prototype.normalizeToRef = function (reference) {
  2980. var len = this.length();
  2981. if (len === 0 || len === 1.0) {
  2982. reference.set(this.x, this.y, this.z);
  2983. return reference;
  2984. }
  2985. var scale = 1.0 / len;
  2986. this.scaleToRef(scale, reference);
  2987. return reference;
  2988. };
  2989. /**
  2990. * Creates a new Vector3 copied from the current Vector3
  2991. * @returns the new Vector3
  2992. */
  2993. Vector3.prototype.clone = function () {
  2994. return new Vector3(this.x, this.y, this.z);
  2995. };
  2996. /**
  2997. * Copies the passed vector coordinates to the current Vector3 ones
  2998. * @param source defines the source Vector3
  2999. * @returns the current updated Vector3
  3000. */
  3001. Vector3.prototype.copyFrom = function (source) {
  3002. this.x = source.x;
  3003. this.y = source.y;
  3004. this.z = source.z;
  3005. return this;
  3006. };
  3007. /**
  3008. * Copies the passed floats to the current Vector3 coordinates
  3009. * @param x defines the x coordinate of the operand
  3010. * @param y defines the y coordinate of the operand
  3011. * @param z defines the z coordinate of the operand
  3012. * @returns the current updated Vector3
  3013. */
  3014. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3015. this.x = x;
  3016. this.y = y;
  3017. this.z = z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Copies the passed floats to the current Vector3 coordinates
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.set = function (x, y, z) {
  3028. return this.copyFromFloats(x, y, z);
  3029. };
  3030. // Statics
  3031. /**
  3032. * Get the clip factor between two vectors
  3033. * @param vector0 defines the first operand
  3034. * @param vector1 defines the second operand
  3035. * @param axis defines the axis to use
  3036. * @param size defines the size along the axis
  3037. * @returns the clip factor
  3038. */
  3039. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3040. var d0 = Vector3.Dot(vector0, axis) - size;
  3041. var d1 = Vector3.Dot(vector1, axis) - size;
  3042. var s = d0 / (d0 - d1);
  3043. return s;
  3044. };
  3045. /**
  3046. * Get angle between two vectors
  3047. * @param vector0 angle between vector0 and vector1
  3048. * @param vector1 angle between vector0 and vector1
  3049. * @param normal direction of the normal
  3050. * @return the angle between vector0 and vector1
  3051. */
  3052. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3053. var v0 = vector0.clone().normalize();
  3054. var v1 = vector1.clone().normalize();
  3055. var dot = Vector3.Dot(v0, v1);
  3056. var n = Vector3.Cross(v0, v1);
  3057. if (Vector3.Dot(n, normal) > 0) {
  3058. return Math.acos(dot);
  3059. }
  3060. return -Math.acos(dot);
  3061. };
  3062. /**
  3063. * Returns a new Vector3 set from the index "offset" of the passed array
  3064. * @param array defines the source array
  3065. * @param offset defines the offset in the source array
  3066. * @returns the new Vector3
  3067. */
  3068. Vector3.FromArray = function (array, offset) {
  3069. if (!offset) {
  3070. offset = 0;
  3071. }
  3072. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3073. };
  3074. /**
  3075. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3076. * This function is deprecated. Use FromArray instead
  3077. * @param array defines the source array
  3078. * @param offset defines the offset in the source array
  3079. * @returns the new Vector3
  3080. */
  3081. Vector3.FromFloatArray = function (array, offset) {
  3082. return Vector3.FromArray(array, offset);
  3083. };
  3084. /**
  3085. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3086. * @param array defines the source array
  3087. * @param offset defines the offset in the source array
  3088. * @param result defines the Vector3 where to store the result
  3089. */
  3090. Vector3.FromArrayToRef = function (array, offset, result) {
  3091. result.x = array[offset];
  3092. result.y = array[offset + 1];
  3093. result.z = array[offset + 2];
  3094. };
  3095. /**
  3096. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3097. * This function is deprecated. Use FromArrayToRef instead.
  3098. * @param array defines the source array
  3099. * @param offset defines the offset in the source array
  3100. * @param result defines the Vector3 where to store the result
  3101. */
  3102. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3103. return Vector3.FromArrayToRef(array, offset, result);
  3104. };
  3105. /**
  3106. * Sets the passed vector "result" with the passed floats.
  3107. * @param x defines the x coordinate of the source
  3108. * @param y defines the y coordinate of the source
  3109. * @param z defines the z coordinate of the source
  3110. * @param result defines the Vector3 where to store the result
  3111. */
  3112. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3113. result.x = x;
  3114. result.y = y;
  3115. result.z = z;
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3119. * @returns a new empty Vector3
  3120. */
  3121. Vector3.Zero = function () {
  3122. return new Vector3(0.0, 0.0, 0.0);
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3126. * @returns a new unit Vector3
  3127. */
  3128. Vector3.One = function () {
  3129. return new Vector3(1.0, 1.0, 1.0);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3133. * @returns a new up Vector3
  3134. */
  3135. Vector3.Up = function () {
  3136. return new Vector3(0.0, 1.0, 0.0);
  3137. };
  3138. /**
  3139. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3140. * @returns a new forward Vector3
  3141. */
  3142. Vector3.Forward = function () {
  3143. return new Vector3(0.0, 0.0, 1.0);
  3144. };
  3145. /**
  3146. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3147. * @returns a new right Vector3
  3148. */
  3149. Vector3.Right = function () {
  3150. return new Vector3(1.0, 0.0, 0.0);
  3151. };
  3152. /**
  3153. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3154. * @returns a new left Vector3
  3155. */
  3156. Vector3.Left = function () {
  3157. return new Vector3(-1.0, 0.0, 0.0);
  3158. };
  3159. /**
  3160. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3161. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3162. * @param vector defines the Vector3 to transform
  3163. * @param transformation defines the transformation matrix
  3164. * @returns the transformed Vector3
  3165. */
  3166. Vector3.TransformCoordinates = function (vector, transformation) {
  3167. var result = Vector3.Zero();
  3168. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3169. return result;
  3170. };
  3171. /**
  3172. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3173. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3174. * @param vector defines the Vector3 to transform
  3175. * @param transformation defines the transformation matrix
  3176. * @param result defines the Vector3 where to store the result
  3177. */
  3178. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3179. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3180. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3181. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3182. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3183. result.x = x / w;
  3184. result.y = y / w;
  3185. result.z = z / w;
  3186. };
  3187. /**
  3188. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3189. * This method computes tranformed coordinates only, not transformed direction vectors
  3190. * @param x define the x coordinate of the source vector
  3191. * @param y define the y coordinate of the source vector
  3192. * @param z define the z coordinate of the source vector
  3193. * @param transformation defines the transformation matrix
  3194. * @param result defines the Vector3 where to store the result
  3195. */
  3196. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3197. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3198. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3199. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3200. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3201. result.x = rx / rw;
  3202. result.y = ry / rw;
  3203. result.z = rz / rw;
  3204. };
  3205. /**
  3206. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3207. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3208. * @param vector defines the Vector3 to transform
  3209. * @param transformation defines the transformation matrix
  3210. * @returns the new Vector3
  3211. */
  3212. Vector3.TransformNormal = function (vector, transformation) {
  3213. var result = Vector3.Zero();
  3214. Vector3.TransformNormalToRef(vector, transformation, result);
  3215. return result;
  3216. };
  3217. /**
  3218. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3219. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3220. * @param vector defines the Vector3 to transform
  3221. * @param transformation defines the transformation matrix
  3222. * @param result defines the Vector3 where to store the result
  3223. */
  3224. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3225. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3226. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3227. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3228. result.x = x;
  3229. result.y = y;
  3230. result.z = z;
  3231. };
  3232. /**
  3233. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3234. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3235. * @param x define the x coordinate of the source vector
  3236. * @param y define the y coordinate of the source vector
  3237. * @param z define the z coordinate of the source vector
  3238. * @param transformation defines the transformation matrix
  3239. * @param result defines the Vector3 where to store the result
  3240. */
  3241. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3242. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3243. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3244. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3245. };
  3246. /**
  3247. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3248. * @param value1 defines the first control point
  3249. * @param value2 defines the second control point
  3250. * @param value3 defines the third control point
  3251. * @param value4 defines the fourth control point
  3252. * @param amount defines the amount on the spline to use
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3256. var squared = amount * amount;
  3257. var cubed = amount * squared;
  3258. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3259. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3260. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3261. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3262. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3263. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3264. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3265. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3266. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3267. return new Vector3(x, y, z);
  3268. };
  3269. /**
  3270. * 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"
  3271. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3272. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3273. * @param value defines the current value
  3274. * @param min defines the lower range value
  3275. * @param max defines the upper range value
  3276. * @returns the new Vector3
  3277. */
  3278. Vector3.Clamp = function (value, min, max) {
  3279. var x = value.x;
  3280. x = (x > max.x) ? max.x : x;
  3281. x = (x < min.x) ? min.x : x;
  3282. var y = value.y;
  3283. y = (y > max.y) ? max.y : y;
  3284. y = (y < min.y) ? min.y : y;
  3285. var z = value.z;
  3286. z = (z > max.z) ? max.z : z;
  3287. z = (z < min.z) ? min.z : z;
  3288. return new Vector3(x, y, z);
  3289. };
  3290. /**
  3291. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3292. * @param value1 defines the first control point
  3293. * @param tangent1 defines the first tangent vector
  3294. * @param value2 defines the second control point
  3295. * @param tangent2 defines the second tangent vector
  3296. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3297. * @returns the new Vector3
  3298. */
  3299. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3300. var squared = amount * amount;
  3301. var cubed = amount * squared;
  3302. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3303. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3304. var part3 = (cubed - (2.0 * squared)) + amount;
  3305. var part4 = cubed - squared;
  3306. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3307. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3308. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3309. return new Vector3(x, y, z);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3313. * @param start defines the start value
  3314. * @param end defines the end value
  3315. * @param amount max defines amount between both (between 0 and 1)
  3316. * @returns the new Vector3
  3317. */
  3318. Vector3.Lerp = function (start, end, amount) {
  3319. var result = new Vector3(0, 0, 0);
  3320. Vector3.LerpToRef(start, end, amount, result);
  3321. return result;
  3322. };
  3323. /**
  3324. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3325. * @param start defines the start value
  3326. * @param end defines the end value
  3327. * @param amount max defines amount between both (between 0 and 1)
  3328. * @param result defines the Vector3 where to store the result
  3329. */
  3330. Vector3.LerpToRef = function (start, end, amount, result) {
  3331. result.x = start.x + ((end.x - start.x) * amount);
  3332. result.y = start.y + ((end.y - start.y) * amount);
  3333. result.z = start.z + ((end.z - start.z) * amount);
  3334. };
  3335. /**
  3336. * Returns the dot product (float) between the vectors "left" and "right"
  3337. * @param left defines the left operand
  3338. * @param right defines the right operand
  3339. * @returns the dot product
  3340. */
  3341. Vector3.Dot = function (left, right) {
  3342. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3346. * The cross product is then orthogonal to both "left" and "right"
  3347. * @param left defines the left operand
  3348. * @param right defines the right operand
  3349. * @returns the cross product
  3350. */
  3351. Vector3.Cross = function (left, right) {
  3352. var result = Vector3.Zero();
  3353. Vector3.CrossToRef(left, right, result);
  3354. return result;
  3355. };
  3356. /**
  3357. * Sets the passed vector "result" with the cross product of "left" and "right"
  3358. * The cross product is then orthogonal to both "left" and "right"
  3359. * @param left defines the left operand
  3360. * @param right defines the right operand
  3361. * @param result defines the Vector3 where to store the result
  3362. */
  3363. Vector3.CrossToRef = function (left, right, result) {
  3364. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3365. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3366. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3367. result.copyFrom(MathTmp.Vector3[0]);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 as the normalization of the passed vector
  3371. * @param vector defines the Vector3 to normalize
  3372. * @returns the new Vector3
  3373. */
  3374. Vector3.Normalize = function (vector) {
  3375. var result = Vector3.Zero();
  3376. Vector3.NormalizeToRef(vector, result);
  3377. return result;
  3378. };
  3379. /**
  3380. * Sets the passed vector "result" with the normalization of the passed first vector
  3381. * @param vector defines the Vector3 to normalize
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.NormalizeToRef = function (vector, result) {
  3385. result.copyFrom(vector);
  3386. result.normalize();
  3387. };
  3388. /**
  3389. * Project a Vector3 onto screen space
  3390. * @param vector defines the Vector3 to project
  3391. * @param world defines the world matrix to use
  3392. * @param transform defines the transform (view x projection) matrix to use
  3393. * @param viewport defines the screen viewport to use
  3394. * @returns the new Vector3
  3395. */
  3396. Vector3.Project = function (vector, world, transform, viewport) {
  3397. var cw = viewport.width;
  3398. var ch = viewport.height;
  3399. var cx = viewport.x;
  3400. var cy = viewport.y;
  3401. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3402. 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);
  3403. var matrix = MathTmp.Matrix[0];
  3404. world.multiplyToRef(transform, matrix);
  3405. matrix.multiplyToRef(viewportMatrix, matrix);
  3406. return Vector3.TransformCoordinates(vector, matrix);
  3407. };
  3408. /**
  3409. * Unproject from screen space to object space
  3410. * @param source defines the screen space Vector3 to use
  3411. * @param viewportWidth defines the current width of the viewport
  3412. * @param viewportHeight defines the current height of the viewport
  3413. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3414. * @param transform defines the transform (view x projection) matrix to use
  3415. * @returns the new Vector3
  3416. */
  3417. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3418. var matrix = MathTmp.Matrix[0];
  3419. world.multiplyToRef(transform, matrix);
  3420. matrix.invert();
  3421. source.x = source.x / viewportWidth * 2 - 1;
  3422. source.y = -(source.y / viewportHeight * 2 - 1);
  3423. var vector = Vector3.TransformCoordinates(source, matrix);
  3424. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3425. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3426. vector = vector.scale(1.0 / num);
  3427. }
  3428. return vector;
  3429. };
  3430. /**
  3431. * Unproject from screen space to object space
  3432. * @param source defines the screen space Vector3 to use
  3433. * @param viewportWidth defines the current width of the viewport
  3434. * @param viewportHeight defines the current height of the viewport
  3435. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3436. * @param view defines the view matrix to use
  3437. * @param projection defines the projection matrix to use
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3441. var result = Vector3.Zero();
  3442. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3443. return result;
  3444. };
  3445. /**
  3446. * Unproject from screen space to object space
  3447. * @param source defines the screen space Vector3 to use
  3448. * @param viewportWidth defines the current width of the viewport
  3449. * @param viewportHeight defines the current height of the viewport
  3450. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3451. * @param view defines the view matrix to use
  3452. * @param projection defines the projection matrix to use
  3453. * @param result defines the Vector3 where to store the result
  3454. */
  3455. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3456. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3457. };
  3458. /**
  3459. * Unproject from screen space to object space
  3460. * @param sourceX defines the screen space x coordinate to use
  3461. * @param sourceY defines the screen space y coordinate to use
  3462. * @param sourceZ defines the screen space z coordinate to use
  3463. * @param viewportWidth defines the current width of the viewport
  3464. * @param viewportHeight defines the current height of the viewport
  3465. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3466. * @param view defines the view matrix to use
  3467. * @param projection defines the projection matrix to use
  3468. * @param result defines the Vector3 where to store the result
  3469. */
  3470. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3471. var matrix = MathTmp.Matrix[0];
  3472. world.multiplyToRef(view, matrix);
  3473. matrix.multiplyToRef(projection, matrix);
  3474. matrix.invert();
  3475. var screenSource = MathTmp.Vector3[0];
  3476. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3477. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3478. screenSource.z = 2 * sourceZ - 1.0;
  3479. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3480. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3481. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3482. result.scaleInPlace(1.0 / num);
  3483. }
  3484. };
  3485. /**
  3486. * Gets the minimal coordinate values between two Vector3
  3487. * @param left defines the first operand
  3488. * @param right defines the second operand
  3489. * @returns the new Vector3
  3490. */
  3491. Vector3.Minimize = function (left, right) {
  3492. var min = left.clone();
  3493. min.minimizeInPlace(right);
  3494. return min;
  3495. };
  3496. /**
  3497. * Gets the maximal coordinate values between two Vector3
  3498. * @param left defines the first operand
  3499. * @param right defines the second operand
  3500. * @returns the new Vector3
  3501. */
  3502. Vector3.Maximize = function (left, right) {
  3503. var max = left.clone();
  3504. max.maximizeInPlace(right);
  3505. return max;
  3506. };
  3507. /**
  3508. * Returns the distance between the vectors "value1" and "value2"
  3509. * @param value1 defines the first operand
  3510. * @param value2 defines the second operand
  3511. * @returns the distance
  3512. */
  3513. Vector3.Distance = function (value1, value2) {
  3514. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3515. };
  3516. /**
  3517. * Returns the squared distance between the vectors "value1" and "value2"
  3518. * @param value1 defines the first operand
  3519. * @param value2 defines the second operand
  3520. * @returns the squared distance
  3521. */
  3522. Vector3.DistanceSquared = function (value1, value2) {
  3523. var x = value1.x - value2.x;
  3524. var y = value1.y - value2.y;
  3525. var z = value1.z - value2.z;
  3526. return (x * x) + (y * y) + (z * z);
  3527. };
  3528. /**
  3529. * Returns a new Vector3 located at the center between "value1" and "value2"
  3530. * @param value1 defines the first operand
  3531. * @param value2 defines the second operand
  3532. * @returns the new Vector3
  3533. */
  3534. Vector3.Center = function (value1, value2) {
  3535. var center = value1.add(value2);
  3536. center.scaleInPlace(0.5);
  3537. return center;
  3538. };
  3539. /**
  3540. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3541. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3542. * to something in order to rotate it from its local system to the given target system
  3543. * Note: axis1, axis2 and axis3 are normalized during this operation
  3544. * @param axis1 defines the first axis
  3545. * @param axis2 defines the second axis
  3546. * @param axis3 defines the third axis
  3547. * @returns a new Vector3
  3548. */
  3549. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3550. var rotation = Vector3.Zero();
  3551. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3552. return rotation;
  3553. };
  3554. /**
  3555. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3556. * @param axis1 defines the first axis
  3557. * @param axis2 defines the second axis
  3558. * @param axis3 defines the third axis
  3559. * @param ref defines the Vector3 where to store the result
  3560. */
  3561. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3562. var quat = MathTmp.Quaternion[0];
  3563. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3564. quat.toEulerAnglesToRef(ref);
  3565. };
  3566. return Vector3;
  3567. }());
  3568. BABYLON.Vector3 = Vector3;
  3569. //Vector4 class created for EulerAngle class conversion to Quaternion
  3570. var Vector4 = /** @class */ (function () {
  3571. /**
  3572. * Creates a Vector4 object from the passed floats.
  3573. */
  3574. function Vector4(x, y, z, w) {
  3575. this.x = x;
  3576. this.y = y;
  3577. this.z = z;
  3578. this.w = w;
  3579. }
  3580. /**
  3581. * Returns the string with the Vector4 coordinates.
  3582. */
  3583. Vector4.prototype.toString = function () {
  3584. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3585. };
  3586. /**
  3587. * Returns the string "Vector4".
  3588. */
  3589. Vector4.prototype.getClassName = function () {
  3590. return "Vector4";
  3591. };
  3592. /**
  3593. * Returns the Vector4 hash code.
  3594. */
  3595. Vector4.prototype.getHashCode = function () {
  3596. var hash = this.x || 0;
  3597. hash = (hash * 397) ^ (this.y || 0);
  3598. hash = (hash * 397) ^ (this.z || 0);
  3599. hash = (hash * 397) ^ (this.w || 0);
  3600. return hash;
  3601. };
  3602. // Operators
  3603. /**
  3604. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3605. */
  3606. Vector4.prototype.asArray = function () {
  3607. var result = new Array();
  3608. this.toArray(result, 0);
  3609. return result;
  3610. };
  3611. /**
  3612. * Populates the passed array from the passed index with the Vector4 coordinates.
  3613. * Returns the Vector4.
  3614. */
  3615. Vector4.prototype.toArray = function (array, index) {
  3616. if (index === undefined) {
  3617. index = 0;
  3618. }
  3619. array[index] = this.x;
  3620. array[index + 1] = this.y;
  3621. array[index + 2] = this.z;
  3622. array[index + 3] = this.w;
  3623. return this;
  3624. };
  3625. /**
  3626. * Adds the passed vector to the current Vector4.
  3627. * Returns the updated Vector4.
  3628. */
  3629. Vector4.prototype.addInPlace = function (otherVector) {
  3630. this.x += otherVector.x;
  3631. this.y += otherVector.y;
  3632. this.z += otherVector.z;
  3633. this.w += otherVector.w;
  3634. return this;
  3635. };
  3636. /**
  3637. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3638. */
  3639. Vector4.prototype.add = function (otherVector) {
  3640. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3641. };
  3642. /**
  3643. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3644. * Returns the current Vector4.
  3645. */
  3646. Vector4.prototype.addToRef = function (otherVector, result) {
  3647. result.x = this.x + otherVector.x;
  3648. result.y = this.y + otherVector.y;
  3649. result.z = this.z + otherVector.z;
  3650. result.w = this.w + otherVector.w;
  3651. return this;
  3652. };
  3653. /**
  3654. * Subtract in place the passed vector from the current Vector4.
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.subtractInPlace = function (otherVector) {
  3658. this.x -= otherVector.x;
  3659. this.y -= otherVector.y;
  3660. this.z -= otherVector.z;
  3661. this.w -= otherVector.w;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3666. */
  3667. Vector4.prototype.subtract = function (otherVector) {
  3668. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3675. result.x = this.x - otherVector.x;
  3676. result.y = this.y - otherVector.y;
  3677. result.z = this.z - otherVector.z;
  3678. result.w = this.w - otherVector.w;
  3679. return this;
  3680. };
  3681. /**
  3682. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3683. */
  3684. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3685. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3686. };
  3687. /**
  3688. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3689. * Returns the current Vector4.
  3690. */
  3691. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3692. result.x = this.x - x;
  3693. result.y = this.y - y;
  3694. result.z = this.z - z;
  3695. result.w = this.w - w;
  3696. return this;
  3697. };
  3698. /**
  3699. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3700. */
  3701. Vector4.prototype.negate = function () {
  3702. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3703. };
  3704. /**
  3705. * Multiplies the current Vector4 coordinates by scale (float).
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.scaleInPlace = function (scale) {
  3709. this.x *= scale;
  3710. this.y *= scale;
  3711. this.z *= scale;
  3712. this.w *= scale;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3717. */
  3718. Vector4.prototype.scale = function (scale) {
  3719. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3720. };
  3721. /**
  3722. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.scaleToRef = function (scale, result) {
  3726. result.x = this.x * scale;
  3727. result.y = this.y * scale;
  3728. result.z = this.z * scale;
  3729. result.w = this.w * scale;
  3730. return this;
  3731. };
  3732. /**
  3733. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3734. */
  3735. Vector4.prototype.equals = function (otherVector) {
  3736. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3737. };
  3738. /**
  3739. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3740. */
  3741. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3742. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3743. return otherVector
  3744. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3745. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3746. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3747. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3748. };
  3749. /**
  3750. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3751. */
  3752. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3753. return this.x === x && this.y === y && this.z === z && this.w === w;
  3754. };
  3755. /**
  3756. * Multiplies in place the current Vector4 by the passed one.
  3757. * Returns the updated Vector4.
  3758. */
  3759. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3760. this.x *= otherVector.x;
  3761. this.y *= otherVector.y;
  3762. this.z *= otherVector.z;
  3763. this.w *= otherVector.w;
  3764. return this;
  3765. };
  3766. /**
  3767. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3768. */
  3769. Vector4.prototype.multiply = function (otherVector) {
  3770. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3771. };
  3772. /**
  3773. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3774. * Returns the current Vector4.
  3775. */
  3776. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3777. result.x = this.x * otherVector.x;
  3778. result.y = this.y * otherVector.y;
  3779. result.z = this.z * otherVector.z;
  3780. result.w = this.w * otherVector.w;
  3781. return this;
  3782. };
  3783. /**
  3784. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3787. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3788. };
  3789. /**
  3790. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3791. */
  3792. Vector4.prototype.divide = function (otherVector) {
  3793. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3794. };
  3795. /**
  3796. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3797. * Returns the current Vector4.
  3798. */
  3799. Vector4.prototype.divideToRef = function (otherVector, result) {
  3800. result.x = this.x / otherVector.x;
  3801. result.y = this.y / otherVector.y;
  3802. result.z = this.z / otherVector.z;
  3803. result.w = this.w / otherVector.w;
  3804. return this;
  3805. };
  3806. /**
  3807. * Divides the current Vector3 coordinates by the passed ones.
  3808. * @returns the updated Vector3.
  3809. */
  3810. Vector4.prototype.divideInPlace = function (otherVector) {
  3811. return this.divideToRef(otherVector, this);
  3812. };
  3813. /**
  3814. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3815. * @param other defines the second operand
  3816. * @returns the current updated Vector4
  3817. */
  3818. Vector4.prototype.minimizeInPlace = function (other) {
  3819. if (other.x < this.x)
  3820. this.x = other.x;
  3821. if (other.y < this.y)
  3822. this.y = other.y;
  3823. if (other.z < this.z)
  3824. this.z = other.z;
  3825. if (other.w < this.w)
  3826. this.w = other.w;
  3827. return this;
  3828. };
  3829. /**
  3830. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3831. * @param other defines the second operand
  3832. * @returns the current updated Vector4
  3833. */
  3834. Vector4.prototype.maximizeInPlace = function (other) {
  3835. if (other.x > this.x)
  3836. this.x = other.x;
  3837. if (other.y > this.y)
  3838. this.y = other.y;
  3839. if (other.z > this.z)
  3840. this.z = other.z;
  3841. if (other.w > this.w)
  3842. this.w = other.w;
  3843. return this;
  3844. };
  3845. // Properties
  3846. /**
  3847. * Returns the Vector4 length (float).
  3848. */
  3849. Vector4.prototype.length = function () {
  3850. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3851. };
  3852. /**
  3853. * Returns the Vector4 squared length (float).
  3854. */
  3855. Vector4.prototype.lengthSquared = function () {
  3856. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3857. };
  3858. // Methods
  3859. /**
  3860. * Normalizes in place the Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.normalize = function () {
  3864. var len = this.length();
  3865. if (len === 0)
  3866. return this;
  3867. var num = 1.0 / len;
  3868. this.x *= num;
  3869. this.y *= num;
  3870. this.z *= num;
  3871. this.w *= num;
  3872. return this;
  3873. };
  3874. /**
  3875. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3876. */
  3877. Vector4.prototype.toVector3 = function () {
  3878. return new Vector3(this.x, this.y, this.z);
  3879. };
  3880. /**
  3881. * Returns a new Vector4 copied from the current one.
  3882. */
  3883. Vector4.prototype.clone = function () {
  3884. return new Vector4(this.x, this.y, this.z, this.w);
  3885. };
  3886. /**
  3887. * Updates the current Vector4 with the passed one coordinates.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.copyFrom = function (source) {
  3891. this.x = source.x;
  3892. this.y = source.y;
  3893. this.z = source.z;
  3894. this.w = source.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Updates the current Vector4 coordinates with the passed floats.
  3899. * Returns the updated Vector4.
  3900. */
  3901. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3902. this.x = x;
  3903. this.y = y;
  3904. this.z = z;
  3905. this.w = w;
  3906. return this;
  3907. };
  3908. /**
  3909. * Updates the current Vector4 coordinates with the passed floats.
  3910. * Returns the updated Vector4.
  3911. */
  3912. Vector4.prototype.set = function (x, y, z, w) {
  3913. return this.copyFromFloats(x, y, z, w);
  3914. };
  3915. // Statics
  3916. /**
  3917. * Returns a new Vector4 set from the starting index of the passed array.
  3918. */
  3919. Vector4.FromArray = function (array, offset) {
  3920. if (!offset) {
  3921. offset = 0;
  3922. }
  3923. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3924. };
  3925. /**
  3926. * Updates the passed vector "result" from the starting index of the passed array.
  3927. */
  3928. Vector4.FromArrayToRef = function (array, offset, result) {
  3929. result.x = array[offset];
  3930. result.y = array[offset + 1];
  3931. result.z = array[offset + 2];
  3932. result.w = array[offset + 3];
  3933. };
  3934. /**
  3935. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3936. */
  3937. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3938. Vector4.FromArrayToRef(array, offset, result);
  3939. };
  3940. /**
  3941. * Updates the passed vector "result" coordinates from the passed floats.
  3942. */
  3943. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3944. result.x = x;
  3945. result.y = y;
  3946. result.z = z;
  3947. result.w = w;
  3948. };
  3949. /**
  3950. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3951. */
  3952. Vector4.Zero = function () {
  3953. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3954. };
  3955. /**
  3956. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3957. */
  3958. Vector4.One = function () {
  3959. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3960. };
  3961. /**
  3962. * Returns a new normalized Vector4 from the passed one.
  3963. */
  3964. Vector4.Normalize = function (vector) {
  3965. var result = Vector4.Zero();
  3966. Vector4.NormalizeToRef(vector, result);
  3967. return result;
  3968. };
  3969. /**
  3970. * Updates the passed vector "result" from the normalization of the passed one.
  3971. */
  3972. Vector4.NormalizeToRef = function (vector, result) {
  3973. result.copyFrom(vector);
  3974. result.normalize();
  3975. };
  3976. Vector4.Minimize = function (left, right) {
  3977. var min = left.clone();
  3978. min.minimizeInPlace(right);
  3979. return min;
  3980. };
  3981. Vector4.Maximize = function (left, right) {
  3982. var max = left.clone();
  3983. max.maximizeInPlace(right);
  3984. return max;
  3985. };
  3986. /**
  3987. * Returns the distance (float) between the vectors "value1" and "value2".
  3988. */
  3989. Vector4.Distance = function (value1, value2) {
  3990. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3991. };
  3992. /**
  3993. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3994. */
  3995. Vector4.DistanceSquared = function (value1, value2) {
  3996. var x = value1.x - value2.x;
  3997. var y = value1.y - value2.y;
  3998. var z = value1.z - value2.z;
  3999. var w = value1.w - value2.w;
  4000. return (x * x) + (y * y) + (z * z) + (w * w);
  4001. };
  4002. /**
  4003. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4004. */
  4005. Vector4.Center = function (value1, value2) {
  4006. var center = value1.add(value2);
  4007. center.scaleInPlace(0.5);
  4008. return center;
  4009. };
  4010. /**
  4011. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4012. * This methods computes transformed normalized direction vectors only.
  4013. */
  4014. Vector4.TransformNormal = function (vector, transformation) {
  4015. var result = Vector4.Zero();
  4016. Vector4.TransformNormalToRef(vector, transformation, result);
  4017. return result;
  4018. };
  4019. /**
  4020. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4021. * This methods computes transformed normalized direction vectors only.
  4022. */
  4023. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4024. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4025. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4026. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4027. result.x = x;
  4028. result.y = y;
  4029. result.z = z;
  4030. result.w = vector.w;
  4031. };
  4032. /**
  4033. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4034. * This methods computes transformed normalized direction vectors only.
  4035. */
  4036. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4037. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4038. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4039. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4040. result.w = w;
  4041. };
  4042. return Vector4;
  4043. }());
  4044. BABYLON.Vector4 = Vector4;
  4045. var Size = /** @class */ (function () {
  4046. /**
  4047. * Creates a Size object from the passed width and height (floats).
  4048. */
  4049. function Size(width, height) {
  4050. this.width = width;
  4051. this.height = height;
  4052. }
  4053. // Returns a string with the Size width and height.
  4054. Size.prototype.toString = function () {
  4055. return "{W: " + this.width + ", H: " + this.height + "}";
  4056. };
  4057. /**
  4058. * Returns the string "Size"
  4059. */
  4060. Size.prototype.getClassName = function () {
  4061. return "Size";
  4062. };
  4063. /**
  4064. * Returns the Size hash code.
  4065. */
  4066. Size.prototype.getHashCode = function () {
  4067. var hash = this.width || 0;
  4068. hash = (hash * 397) ^ (this.height || 0);
  4069. return hash;
  4070. };
  4071. /**
  4072. * Updates the current size from the passed one.
  4073. * Returns the updated Size.
  4074. */
  4075. Size.prototype.copyFrom = function (src) {
  4076. this.width = src.width;
  4077. this.height = src.height;
  4078. };
  4079. /**
  4080. * Updates in place the current Size from the passed floats.
  4081. * Returns the updated Size.
  4082. */
  4083. Size.prototype.copyFromFloats = function (width, height) {
  4084. this.width = width;
  4085. this.height = height;
  4086. return this;
  4087. };
  4088. /**
  4089. * Updates in place the current Size from the passed floats.
  4090. * Returns the updated Size.
  4091. */
  4092. Size.prototype.set = function (width, height) {
  4093. return this.copyFromFloats(width, height);
  4094. };
  4095. /**
  4096. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4097. */
  4098. Size.prototype.multiplyByFloats = function (w, h) {
  4099. return new Size(this.width * w, this.height * h);
  4100. };
  4101. /**
  4102. * Returns a new Size copied from the passed one.
  4103. */
  4104. Size.prototype.clone = function () {
  4105. return new Size(this.width, this.height);
  4106. };
  4107. /**
  4108. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4109. */
  4110. Size.prototype.equals = function (other) {
  4111. if (!other) {
  4112. return false;
  4113. }
  4114. return (this.width === other.width) && (this.height === other.height);
  4115. };
  4116. Object.defineProperty(Size.prototype, "surface", {
  4117. /**
  4118. * Returns the surface of the Size : width * height (float).
  4119. */
  4120. get: function () {
  4121. return this.width * this.height;
  4122. },
  4123. enumerable: true,
  4124. configurable: true
  4125. });
  4126. /**
  4127. * Returns a new Size set to (0.0, 0.0)
  4128. */
  4129. Size.Zero = function () {
  4130. return new Size(0.0, 0.0);
  4131. };
  4132. /**
  4133. * Returns a new Size set as the addition result of the current Size and the passed one.
  4134. */
  4135. Size.prototype.add = function (otherSize) {
  4136. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4137. return r;
  4138. };
  4139. /**
  4140. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4141. */
  4142. Size.prototype.subtract = function (otherSize) {
  4143. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4144. return r;
  4145. };
  4146. /**
  4147. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4148. */
  4149. Size.Lerp = function (start, end, amount) {
  4150. var w = start.width + ((end.width - start.width) * amount);
  4151. var h = start.height + ((end.height - start.height) * amount);
  4152. return new Size(w, h);
  4153. };
  4154. return Size;
  4155. }());
  4156. BABYLON.Size = Size;
  4157. var Quaternion = /** @class */ (function () {
  4158. /**
  4159. * Creates a new Quaternion from the passed floats.
  4160. */
  4161. function Quaternion(x, y, z, w) {
  4162. if (x === void 0) { x = 0.0; }
  4163. if (y === void 0) { y = 0.0; }
  4164. if (z === void 0) { z = 0.0; }
  4165. if (w === void 0) { w = 1.0; }
  4166. this.x = x;
  4167. this.y = y;
  4168. this.z = z;
  4169. this.w = w;
  4170. }
  4171. /**
  4172. * Returns a string with the Quaternion coordinates.
  4173. */
  4174. Quaternion.prototype.toString = function () {
  4175. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4176. };
  4177. /**
  4178. * Returns the string "Quaternion".
  4179. */
  4180. Quaternion.prototype.getClassName = function () {
  4181. return "Quaternion";
  4182. };
  4183. /**
  4184. * Returns the Quaternion hash code.
  4185. */
  4186. Quaternion.prototype.getHashCode = function () {
  4187. var hash = this.x || 0;
  4188. hash = (hash * 397) ^ (this.y || 0);
  4189. hash = (hash * 397) ^ (this.z || 0);
  4190. hash = (hash * 397) ^ (this.w || 0);
  4191. return hash;
  4192. };
  4193. /**
  4194. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4195. */
  4196. Quaternion.prototype.asArray = function () {
  4197. return [this.x, this.y, this.z, this.w];
  4198. };
  4199. /**
  4200. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4201. */
  4202. Quaternion.prototype.equals = function (otherQuaternion) {
  4203. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4204. };
  4205. /**
  4206. * Returns a new Quaternion copied from the current one.
  4207. */
  4208. Quaternion.prototype.clone = function () {
  4209. return new Quaternion(this.x, this.y, this.z, this.w);
  4210. };
  4211. /**
  4212. * Updates the current Quaternion from the passed one coordinates.
  4213. * Returns the updated Quaterion.
  4214. */
  4215. Quaternion.prototype.copyFrom = function (other) {
  4216. this.x = other.x;
  4217. this.y = other.y;
  4218. this.z = other.z;
  4219. this.w = other.w;
  4220. return this;
  4221. };
  4222. /**
  4223. * Updates the current Quaternion from the passed float coordinates.
  4224. * Returns the updated Quaterion.
  4225. */
  4226. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4227. this.x = x;
  4228. this.y = y;
  4229. this.z = z;
  4230. this.w = w;
  4231. return this;
  4232. };
  4233. /**
  4234. * Updates the current Quaternion from the passed float coordinates.
  4235. * Returns the updated Quaterion.
  4236. */
  4237. Quaternion.prototype.set = function (x, y, z, w) {
  4238. return this.copyFromFloats(x, y, z, w);
  4239. };
  4240. /**
  4241. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4242. */
  4243. Quaternion.prototype.add = function (other) {
  4244. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4245. };
  4246. /**
  4247. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4248. */
  4249. Quaternion.prototype.subtract = function (other) {
  4250. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4251. };
  4252. /**
  4253. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4254. */
  4255. Quaternion.prototype.scale = function (value) {
  4256. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4257. };
  4258. /**
  4259. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4260. */
  4261. Quaternion.prototype.multiply = function (q1) {
  4262. var result = new Quaternion(0, 0, 0, 1.0);
  4263. this.multiplyToRef(q1, result);
  4264. return result;
  4265. };
  4266. /**
  4267. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4268. * Returns the current Quaternion.
  4269. */
  4270. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4271. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4272. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4273. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4274. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4275. result.copyFromFloats(x, y, z, w);
  4276. return this;
  4277. };
  4278. /**
  4279. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4280. * Returns the updated Quaternion.
  4281. */
  4282. Quaternion.prototype.multiplyInPlace = function (q1) {
  4283. this.multiplyToRef(q1, this);
  4284. return this;
  4285. };
  4286. /**
  4287. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4288. * Returns the current Quaternion.
  4289. */
  4290. Quaternion.prototype.conjugateToRef = function (ref) {
  4291. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4292. return this;
  4293. };
  4294. /**
  4295. * Conjugates in place the current Quaternion.
  4296. * Returns the updated Quaternion.
  4297. */
  4298. Quaternion.prototype.conjugateInPlace = function () {
  4299. this.x *= -1;
  4300. this.y *= -1;
  4301. this.z *= -1;
  4302. return this;
  4303. };
  4304. /**
  4305. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4306. */
  4307. Quaternion.prototype.conjugate = function () {
  4308. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4309. return result;
  4310. };
  4311. /**
  4312. * Returns the Quaternion length (float).
  4313. */
  4314. Quaternion.prototype.length = function () {
  4315. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4316. };
  4317. /**
  4318. * Normalize in place the current Quaternion.
  4319. * Returns the updated Quaternion.
  4320. */
  4321. Quaternion.prototype.normalize = function () {
  4322. var length = 1.0 / this.length();
  4323. this.x *= length;
  4324. this.y *= length;
  4325. this.z *= length;
  4326. this.w *= length;
  4327. return this;
  4328. };
  4329. /**
  4330. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4331. */
  4332. Quaternion.prototype.toEulerAngles = function (order) {
  4333. if (order === void 0) { order = "YZX"; }
  4334. var result = Vector3.Zero();
  4335. this.toEulerAnglesToRef(result, order);
  4336. return result;
  4337. };
  4338. /**
  4339. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4340. * Returns the current Quaternion.
  4341. */
  4342. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4343. if (order === void 0) { order = "YZX"; }
  4344. var qz = this.z;
  4345. var qx = this.x;
  4346. var qy = this.y;
  4347. var qw = this.w;
  4348. var sqw = qw * qw;
  4349. var sqz = qz * qz;
  4350. var sqx = qx * qx;
  4351. var sqy = qy * qy;
  4352. var zAxisY = qy * qz - qx * qw;
  4353. var limit = .4999999;
  4354. if (zAxisY < -limit) {
  4355. result.y = 2 * Math.atan2(qy, qw);
  4356. result.x = Math.PI / 2;
  4357. result.z = 0;
  4358. }
  4359. else if (zAxisY > limit) {
  4360. result.y = 2 * Math.atan2(qy, qw);
  4361. result.x = -Math.PI / 2;
  4362. result.z = 0;
  4363. }
  4364. else {
  4365. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4366. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4367. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4368. }
  4369. return this;
  4370. };
  4371. /**
  4372. * Updates the passed rotation matrix with the current Quaternion values.
  4373. * Returns the current Quaternion.
  4374. */
  4375. Quaternion.prototype.toRotationMatrix = function (result) {
  4376. var xx = this.x * this.x;
  4377. var yy = this.y * this.y;
  4378. var zz = this.z * this.z;
  4379. var xy = this.x * this.y;
  4380. var zw = this.z * this.w;
  4381. var zx = this.z * this.x;
  4382. var yw = this.y * this.w;
  4383. var yz = this.y * this.z;
  4384. var xw = this.x * this.w;
  4385. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4386. result.m[1] = 2.0 * (xy + zw);
  4387. result.m[2] = 2.0 * (zx - yw);
  4388. result.m[3] = 0;
  4389. result.m[4] = 2.0 * (xy - zw);
  4390. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4391. result.m[6] = 2.0 * (yz + xw);
  4392. result.m[7] = 0;
  4393. result.m[8] = 2.0 * (zx + yw);
  4394. result.m[9] = 2.0 * (yz - xw);
  4395. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4396. result.m[11] = 0;
  4397. result.m[12] = 0;
  4398. result.m[13] = 0;
  4399. result.m[14] = 0;
  4400. result.m[15] = 1.0;
  4401. result._markAsUpdated();
  4402. return this;
  4403. };
  4404. /**
  4405. * Updates the current Quaternion from the passed rotation matrix values.
  4406. * Returns the updated Quaternion.
  4407. */
  4408. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4409. Quaternion.FromRotationMatrixToRef(matrix, this);
  4410. return this;
  4411. };
  4412. // Statics
  4413. /**
  4414. * Returns a new Quaternion set from the passed rotation matrix values.
  4415. */
  4416. Quaternion.FromRotationMatrix = function (matrix) {
  4417. var result = new Quaternion();
  4418. Quaternion.FromRotationMatrixToRef(matrix, result);
  4419. return result;
  4420. };
  4421. /**
  4422. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4423. */
  4424. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4425. var data = matrix.m;
  4426. var m11 = data[0], m12 = data[4], m13 = data[8];
  4427. var m21 = data[1], m22 = data[5], m23 = data[9];
  4428. var m31 = data[2], m32 = data[6], m33 = data[10];
  4429. var trace = m11 + m22 + m33;
  4430. var s;
  4431. if (trace > 0) {
  4432. s = 0.5 / Math.sqrt(trace + 1.0);
  4433. result.w = 0.25 / s;
  4434. result.x = (m32 - m23) * s;
  4435. result.y = (m13 - m31) * s;
  4436. result.z = (m21 - m12) * s;
  4437. }
  4438. else if (m11 > m22 && m11 > m33) {
  4439. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4440. result.w = (m32 - m23) / s;
  4441. result.x = 0.25 * s;
  4442. result.y = (m12 + m21) / s;
  4443. result.z = (m13 + m31) / s;
  4444. }
  4445. else if (m22 > m33) {
  4446. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4447. result.w = (m13 - m31) / s;
  4448. result.x = (m12 + m21) / s;
  4449. result.y = 0.25 * s;
  4450. result.z = (m23 + m32) / s;
  4451. }
  4452. else {
  4453. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4454. result.w = (m21 - m12) / s;
  4455. result.x = (m13 + m31) / s;
  4456. result.y = (m23 + m32) / s;
  4457. result.z = 0.25 * s;
  4458. }
  4459. };
  4460. /**
  4461. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4462. */
  4463. Quaternion.Zero = function () {
  4464. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4465. };
  4466. /**
  4467. * Returns a new Quaternion as the inverted current Quaternion.
  4468. */
  4469. Quaternion.Inverse = function (q) {
  4470. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4471. };
  4472. /**
  4473. * Returns the identity Quaternion.
  4474. */
  4475. Quaternion.Identity = function () {
  4476. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4477. };
  4478. Quaternion.IsIdentity = function (quaternion) {
  4479. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4480. };
  4481. /**
  4482. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4483. */
  4484. Quaternion.RotationAxis = function (axis, angle) {
  4485. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4486. };
  4487. /**
  4488. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4489. */
  4490. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4491. var sin = Math.sin(angle / 2);
  4492. axis.normalize();
  4493. result.w = Math.cos(angle / 2);
  4494. result.x = axis.x * sin;
  4495. result.y = axis.y * sin;
  4496. result.z = axis.z * sin;
  4497. return result;
  4498. };
  4499. /**
  4500. * Retuns a new Quaternion set from the starting index of the passed array.
  4501. */
  4502. Quaternion.FromArray = function (array, offset) {
  4503. if (!offset) {
  4504. offset = 0;
  4505. }
  4506. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4507. };
  4508. /**
  4509. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4510. */
  4511. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4512. var q = new Quaternion();
  4513. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4514. return q;
  4515. };
  4516. /**
  4517. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4518. */
  4519. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4520. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4521. var halfRoll = roll * 0.5;
  4522. var halfPitch = pitch * 0.5;
  4523. var halfYaw = yaw * 0.5;
  4524. var sinRoll = Math.sin(halfRoll);
  4525. var cosRoll = Math.cos(halfRoll);
  4526. var sinPitch = Math.sin(halfPitch);
  4527. var cosPitch = Math.cos(halfPitch);
  4528. var sinYaw = Math.sin(halfYaw);
  4529. var cosYaw = Math.cos(halfYaw);
  4530. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4531. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4532. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4533. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4534. };
  4535. /**
  4536. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4537. */
  4538. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4539. var result = new Quaternion();
  4540. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4541. return result;
  4542. };
  4543. /**
  4544. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4545. */
  4546. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4547. // Produces a quaternion from Euler angles in the z-x-z orientation
  4548. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4549. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4550. var halfBeta = beta * 0.5;
  4551. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4552. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4553. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4554. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4555. };
  4556. /**
  4557. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4558. * cf to Vector3.RotationFromAxis() documentation.
  4559. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4560. */
  4561. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4562. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4563. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4564. return quat;
  4565. };
  4566. /**
  4567. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4568. * cf to Vector3.RotationFromAxis() documentation.
  4569. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4570. */
  4571. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4572. var rotMat = MathTmp.Matrix[0];
  4573. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4574. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4575. };
  4576. Quaternion.Slerp = function (left, right, amount) {
  4577. var result = Quaternion.Identity();
  4578. Quaternion.SlerpToRef(left, right, amount, result);
  4579. return result;
  4580. };
  4581. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4582. var num2;
  4583. var num3;
  4584. var num = amount;
  4585. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4586. var flag = false;
  4587. if (num4 < 0) {
  4588. flag = true;
  4589. num4 = -num4;
  4590. }
  4591. if (num4 > 0.999999) {
  4592. num3 = 1 - num;
  4593. num2 = flag ? -num : num;
  4594. }
  4595. else {
  4596. var num5 = Math.acos(num4);
  4597. var num6 = (1.0 / Math.sin(num5));
  4598. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4599. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4600. }
  4601. result.x = (num3 * left.x) + (num2 * right.x);
  4602. result.y = (num3 * left.y) + (num2 * right.y);
  4603. result.z = (num3 * left.z) + (num2 * right.z);
  4604. result.w = (num3 * left.w) + (num2 * right.w);
  4605. };
  4606. /**
  4607. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4608. */
  4609. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4610. var squared = amount * amount;
  4611. var cubed = amount * squared;
  4612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4614. var part3 = (cubed - (2.0 * squared)) + amount;
  4615. var part4 = cubed - squared;
  4616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4619. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4620. return new Quaternion(x, y, z, w);
  4621. };
  4622. return Quaternion;
  4623. }());
  4624. BABYLON.Quaternion = Quaternion;
  4625. var Matrix = /** @class */ (function () {
  4626. function Matrix() {
  4627. this._isIdentity = false;
  4628. this._isIdentityDirty = true;
  4629. this.m = new Float32Array(16);
  4630. this._markAsUpdated();
  4631. }
  4632. Matrix.prototype._markAsUpdated = function () {
  4633. this.updateFlag = Matrix._updateFlagSeed++;
  4634. this._isIdentityDirty = true;
  4635. };
  4636. // Properties
  4637. /**
  4638. * Boolean : True is the matrix is the identity matrix
  4639. */
  4640. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4641. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4642. if (this._isIdentityDirty) {
  4643. this._isIdentityDirty = false;
  4644. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4645. this._isIdentity = false;
  4646. }
  4647. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4648. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4649. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4650. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4651. this._isIdentity = false;
  4652. }
  4653. else {
  4654. this._isIdentity = true;
  4655. }
  4656. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4657. this._isIdentity = false;
  4658. }
  4659. }
  4660. return this._isIdentity;
  4661. };
  4662. /**
  4663. * Returns the matrix determinant (float).
  4664. */
  4665. Matrix.prototype.determinant = function () {
  4666. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4667. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4668. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4669. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4670. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4671. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4672. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4673. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4674. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4675. };
  4676. // Methods
  4677. /**
  4678. * Returns the matrix underlying array.
  4679. */
  4680. Matrix.prototype.toArray = function () {
  4681. return this.m;
  4682. };
  4683. /**
  4684. * Returns the matrix underlying array.
  4685. */
  4686. Matrix.prototype.asArray = function () {
  4687. return this.toArray();
  4688. };
  4689. /**
  4690. * Inverts in place the Matrix.
  4691. * Returns the Matrix inverted.
  4692. */
  4693. Matrix.prototype.invert = function () {
  4694. this.invertToRef(this);
  4695. return this;
  4696. };
  4697. /**
  4698. * Sets all the matrix elements to zero.
  4699. * Returns the Matrix.
  4700. */
  4701. Matrix.prototype.reset = function () {
  4702. for (var index = 0; index < 16; index++) {
  4703. this.m[index] = 0.0;
  4704. }
  4705. this._markAsUpdated();
  4706. return this;
  4707. };
  4708. /**
  4709. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4710. */
  4711. Matrix.prototype.add = function (other) {
  4712. var result = new Matrix();
  4713. this.addToRef(other, result);
  4714. return result;
  4715. };
  4716. /**
  4717. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4718. * Returns the Matrix.
  4719. */
  4720. Matrix.prototype.addToRef = function (other, result) {
  4721. for (var index = 0; index < 16; index++) {
  4722. result.m[index] = this.m[index] + other.m[index];
  4723. }
  4724. result._markAsUpdated();
  4725. return this;
  4726. };
  4727. /**
  4728. * Adds in place the passed matrix to the current Matrix.
  4729. * Returns the updated Matrix.
  4730. */
  4731. Matrix.prototype.addToSelf = function (other) {
  4732. for (var index = 0; index < 16; index++) {
  4733. this.m[index] += other.m[index];
  4734. }
  4735. this._markAsUpdated();
  4736. return this;
  4737. };
  4738. /**
  4739. * Sets the passed matrix with the current inverted Matrix.
  4740. * Returns the unmodified current Matrix.
  4741. */
  4742. Matrix.prototype.invertToRef = function (other) {
  4743. var l1 = this.m[0];
  4744. var l2 = this.m[1];
  4745. var l3 = this.m[2];
  4746. var l4 = this.m[3];
  4747. var l5 = this.m[4];
  4748. var l6 = this.m[5];
  4749. var l7 = this.m[6];
  4750. var l8 = this.m[7];
  4751. var l9 = this.m[8];
  4752. var l10 = this.m[9];
  4753. var l11 = this.m[10];
  4754. var l12 = this.m[11];
  4755. var l13 = this.m[12];
  4756. var l14 = this.m[13];
  4757. var l15 = this.m[14];
  4758. var l16 = this.m[15];
  4759. var l17 = (l11 * l16) - (l12 * l15);
  4760. var l18 = (l10 * l16) - (l12 * l14);
  4761. var l19 = (l10 * l15) - (l11 * l14);
  4762. var l20 = (l9 * l16) - (l12 * l13);
  4763. var l21 = (l9 * l15) - (l11 * l13);
  4764. var l22 = (l9 * l14) - (l10 * l13);
  4765. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4766. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4767. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4768. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4769. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4770. var l28 = (l7 * l16) - (l8 * l15);
  4771. var l29 = (l6 * l16) - (l8 * l14);
  4772. var l30 = (l6 * l15) - (l7 * l14);
  4773. var l31 = (l5 * l16) - (l8 * l13);
  4774. var l32 = (l5 * l15) - (l7 * l13);
  4775. var l33 = (l5 * l14) - (l6 * l13);
  4776. var l34 = (l7 * l12) - (l8 * l11);
  4777. var l35 = (l6 * l12) - (l8 * l10);
  4778. var l36 = (l6 * l11) - (l7 * l10);
  4779. var l37 = (l5 * l12) - (l8 * l9);
  4780. var l38 = (l5 * l11) - (l7 * l9);
  4781. var l39 = (l5 * l10) - (l6 * l9);
  4782. other.m[0] = l23 * l27;
  4783. other.m[4] = l24 * l27;
  4784. other.m[8] = l25 * l27;
  4785. other.m[12] = l26 * l27;
  4786. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4787. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4788. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4789. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4790. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4791. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4792. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4793. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4794. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4795. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4796. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4797. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4798. other._markAsUpdated();
  4799. return this;
  4800. };
  4801. /**
  4802. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4803. * Returns the updated Matrix.
  4804. */
  4805. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4806. this.m[12] = x;
  4807. this.m[13] = y;
  4808. this.m[14] = z;
  4809. this._markAsUpdated();
  4810. return this;
  4811. };
  4812. /**
  4813. * Inserts the translation vector in the current Matrix.
  4814. * Returns the updated Matrix.
  4815. */
  4816. Matrix.prototype.setTranslation = function (vector3) {
  4817. this.m[12] = vector3.x;
  4818. this.m[13] = vector3.y;
  4819. this.m[14] = vector3.z;
  4820. this._markAsUpdated();
  4821. return this;
  4822. };
  4823. /**
  4824. * Returns a new Vector3 as the extracted translation from the Matrix.
  4825. */
  4826. Matrix.prototype.getTranslation = function () {
  4827. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4828. };
  4829. /**
  4830. * Fill a Vector3 with the extracted translation from the Matrix.
  4831. */
  4832. Matrix.prototype.getTranslationToRef = function (result) {
  4833. result.x = this.m[12];
  4834. result.y = this.m[13];
  4835. result.z = this.m[14];
  4836. return this;
  4837. };
  4838. /**
  4839. * Remove rotation and scaling part from the Matrix.
  4840. * Returns the updated Matrix.
  4841. */
  4842. Matrix.prototype.removeRotationAndScaling = function () {
  4843. this.setRowFromFloats(0, 1, 0, 0, 0);
  4844. this.setRowFromFloats(1, 0, 1, 0, 0);
  4845. this.setRowFromFloats(2, 0, 0, 1, 0);
  4846. return this;
  4847. };
  4848. /**
  4849. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4850. */
  4851. Matrix.prototype.multiply = function (other) {
  4852. var result = new Matrix();
  4853. this.multiplyToRef(other, result);
  4854. return result;
  4855. };
  4856. /**
  4857. * Updates the current Matrix from the passed one values.
  4858. * Returns the updated Matrix.
  4859. */
  4860. Matrix.prototype.copyFrom = function (other) {
  4861. for (var index = 0; index < 16; index++) {
  4862. this.m[index] = other.m[index];
  4863. }
  4864. this._markAsUpdated();
  4865. return this;
  4866. };
  4867. /**
  4868. * Populates the passed array from the starting index with the Matrix values.
  4869. * Returns the Matrix.
  4870. */
  4871. Matrix.prototype.copyToArray = function (array, offset) {
  4872. if (offset === void 0) { offset = 0; }
  4873. for (var index = 0; index < 16; index++) {
  4874. array[offset + index] = this.m[index];
  4875. }
  4876. return this;
  4877. };
  4878. /**
  4879. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4880. */
  4881. Matrix.prototype.multiplyToRef = function (other, result) {
  4882. this.multiplyToArray(other, result.m, 0);
  4883. result._markAsUpdated();
  4884. return this;
  4885. };
  4886. /**
  4887. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4888. */
  4889. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4890. var tm0 = this.m[0];
  4891. var tm1 = this.m[1];
  4892. var tm2 = this.m[2];
  4893. var tm3 = this.m[3];
  4894. var tm4 = this.m[4];
  4895. var tm5 = this.m[5];
  4896. var tm6 = this.m[6];
  4897. var tm7 = this.m[7];
  4898. var tm8 = this.m[8];
  4899. var tm9 = this.m[9];
  4900. var tm10 = this.m[10];
  4901. var tm11 = this.m[11];
  4902. var tm12 = this.m[12];
  4903. var tm13 = this.m[13];
  4904. var tm14 = this.m[14];
  4905. var tm15 = this.m[15];
  4906. var om0 = other.m[0];
  4907. var om1 = other.m[1];
  4908. var om2 = other.m[2];
  4909. var om3 = other.m[3];
  4910. var om4 = other.m[4];
  4911. var om5 = other.m[5];
  4912. var om6 = other.m[6];
  4913. var om7 = other.m[7];
  4914. var om8 = other.m[8];
  4915. var om9 = other.m[9];
  4916. var om10 = other.m[10];
  4917. var om11 = other.m[11];
  4918. var om12 = other.m[12];
  4919. var om13 = other.m[13];
  4920. var om14 = other.m[14];
  4921. var om15 = other.m[15];
  4922. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4923. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4924. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4925. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4926. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4927. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4928. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4929. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4930. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4931. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4932. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4933. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4934. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4935. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4936. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4937. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4938. return this;
  4939. };
  4940. /**
  4941. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4942. */
  4943. Matrix.prototype.equals = function (value) {
  4944. return value &&
  4945. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4946. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4947. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4948. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4949. };
  4950. /**
  4951. * Returns a new Matrix from the current Matrix.
  4952. */
  4953. Matrix.prototype.clone = function () {
  4954. 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]);
  4955. };
  4956. /**
  4957. * Returns the string "Matrix"
  4958. */
  4959. Matrix.prototype.getClassName = function () {
  4960. return "Matrix";
  4961. };
  4962. /**
  4963. * Returns the Matrix hash code.
  4964. */
  4965. Matrix.prototype.getHashCode = function () {
  4966. var hash = this.m[0] || 0;
  4967. for (var i = 1; i < 16; i++) {
  4968. hash = (hash * 397) ^ (this.m[i] || 0);
  4969. }
  4970. return hash;
  4971. };
  4972. /**
  4973. * Decomposes the current Matrix into :
  4974. * - a scale vector3 passed as a reference to update,
  4975. * - a rotation quaternion passed as a reference to update,
  4976. * - a translation vector3 passed as a reference to update.
  4977. * Returns the true if operation was successful.
  4978. */
  4979. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4980. translation.x = this.m[12];
  4981. translation.y = this.m[13];
  4982. translation.z = this.m[14];
  4983. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4984. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4985. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4986. if (this.determinant() <= 0) {
  4987. scale.y *= -1;
  4988. }
  4989. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4990. rotation.x = 0;
  4991. rotation.y = 0;
  4992. rotation.z = 0;
  4993. rotation.w = 1;
  4994. return false;
  4995. }
  4996. 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]);
  4997. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4998. return true;
  4999. };
  5000. /**
  5001. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5002. * @param ref matrix to store the result
  5003. */
  5004. Matrix.prototype.toNormalMatrix = function (ref) {
  5005. this.invertToRef(ref);
  5006. ref.transpose();
  5007. var m = ref.m;
  5008. 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);
  5009. };
  5010. /**
  5011. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5012. */
  5013. Matrix.prototype.getRotationMatrix = function () {
  5014. var result = Matrix.Identity();
  5015. this.getRotationMatrixToRef(result);
  5016. return result;
  5017. };
  5018. /**
  5019. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5020. * Returns the current Matrix.
  5021. */
  5022. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5023. var m = this.m;
  5024. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5025. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5026. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5027. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5028. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5029. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5030. 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);
  5031. return this;
  5032. };
  5033. // Statics
  5034. /**
  5035. * Returns a new Matrix set from the starting index of the passed array.
  5036. */
  5037. Matrix.FromArray = function (array, offset) {
  5038. var result = new Matrix();
  5039. if (!offset) {
  5040. offset = 0;
  5041. }
  5042. Matrix.FromArrayToRef(array, offset, result);
  5043. return result;
  5044. };
  5045. /**
  5046. * Sets the passed "result" matrix from the starting index of the passed array.
  5047. */
  5048. Matrix.FromArrayToRef = function (array, offset, result) {
  5049. for (var index = 0; index < 16; index++) {
  5050. result.m[index] = array[index + offset];
  5051. }
  5052. result._markAsUpdated();
  5053. };
  5054. /**
  5055. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5056. */
  5057. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5058. for (var index = 0; index < 16; index++) {
  5059. result.m[index] = array[index + offset] * scale;
  5060. }
  5061. result._markAsUpdated();
  5062. };
  5063. /**
  5064. * Sets the passed matrix "result" with the 16 passed floats.
  5065. */
  5066. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5067. result.m[0] = initialM11;
  5068. result.m[1] = initialM12;
  5069. result.m[2] = initialM13;
  5070. result.m[3] = initialM14;
  5071. result.m[4] = initialM21;
  5072. result.m[5] = initialM22;
  5073. result.m[6] = initialM23;
  5074. result.m[7] = initialM24;
  5075. result.m[8] = initialM31;
  5076. result.m[9] = initialM32;
  5077. result.m[10] = initialM33;
  5078. result.m[11] = initialM34;
  5079. result.m[12] = initialM41;
  5080. result.m[13] = initialM42;
  5081. result.m[14] = initialM43;
  5082. result.m[15] = initialM44;
  5083. result._markAsUpdated();
  5084. };
  5085. /**
  5086. * Returns the index-th row of the current matrix as a new Vector4.
  5087. */
  5088. Matrix.prototype.getRow = function (index) {
  5089. if (index < 0 || index > 3) {
  5090. return null;
  5091. }
  5092. var i = index * 4;
  5093. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5094. };
  5095. /**
  5096. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5097. * Returns the updated Matrix.
  5098. */
  5099. Matrix.prototype.setRow = function (index, row) {
  5100. if (index < 0 || index > 3) {
  5101. return this;
  5102. }
  5103. var i = index * 4;
  5104. this.m[i + 0] = row.x;
  5105. this.m[i + 1] = row.y;
  5106. this.m[i + 2] = row.z;
  5107. this.m[i + 3] = row.w;
  5108. this._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Compute the transpose of the matrix.
  5113. * Returns a new Matrix.
  5114. */
  5115. Matrix.prototype.transpose = function () {
  5116. return Matrix.Transpose(this);
  5117. };
  5118. /**
  5119. * Compute the transpose of the matrix.
  5120. * Returns the current matrix.
  5121. */
  5122. Matrix.prototype.transposeToRef = function (result) {
  5123. Matrix.TransposeToRef(this, result);
  5124. return this;
  5125. };
  5126. /**
  5127. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5128. * Returns the updated Matrix.
  5129. */
  5130. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5131. if (index < 0 || index > 3) {
  5132. return this;
  5133. }
  5134. var i = index * 4;
  5135. this.m[i + 0] = x;
  5136. this.m[i + 1] = y;
  5137. this.m[i + 2] = z;
  5138. this.m[i + 3] = w;
  5139. this._markAsUpdated();
  5140. return this;
  5141. };
  5142. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5143. /**
  5144. * Static identity matrix to be used as readonly matrix
  5145. * Must not be updated.
  5146. */
  5147. get: function () {
  5148. return Matrix._identityReadOnly;
  5149. },
  5150. enumerable: true,
  5151. configurable: true
  5152. });
  5153. /**
  5154. * Returns a new Matrix set from the 16 passed floats.
  5155. */
  5156. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5157. var result = new Matrix();
  5158. result.m[0] = initialM11;
  5159. result.m[1] = initialM12;
  5160. result.m[2] = initialM13;
  5161. result.m[3] = initialM14;
  5162. result.m[4] = initialM21;
  5163. result.m[5] = initialM22;
  5164. result.m[6] = initialM23;
  5165. result.m[7] = initialM24;
  5166. result.m[8] = initialM31;
  5167. result.m[9] = initialM32;
  5168. result.m[10] = initialM33;
  5169. result.m[11] = initialM34;
  5170. result.m[12] = initialM41;
  5171. result.m[13] = initialM42;
  5172. result.m[14] = initialM43;
  5173. result.m[15] = initialM44;
  5174. return result;
  5175. };
  5176. /**
  5177. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5178. */
  5179. Matrix.Compose = function (scale, rotation, translation) {
  5180. var result = Matrix.Identity();
  5181. Matrix.ComposeToRef(scale, rotation, translation, result);
  5182. return result;
  5183. };
  5184. /**
  5185. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5186. */
  5187. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5188. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5189. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5190. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5191. result.setTranslation(translation);
  5192. };
  5193. /**
  5194. * Returns a new indentity Matrix.
  5195. */
  5196. Matrix.Identity = function () {
  5197. 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);
  5198. };
  5199. /**
  5200. * Sets the passed "result" as an identity matrix.
  5201. */
  5202. Matrix.IdentityToRef = function (result) {
  5203. 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);
  5204. };
  5205. /**
  5206. * Returns a new zero Matrix.
  5207. */
  5208. Matrix.Zero = function () {
  5209. 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);
  5210. };
  5211. /**
  5212. * Returns a new rotation matrix for "angle" radians around the X axis.
  5213. */
  5214. Matrix.RotationX = function (angle) {
  5215. var result = new Matrix();
  5216. Matrix.RotationXToRef(angle, result);
  5217. return result;
  5218. };
  5219. /**
  5220. * Returns a new Matrix as the passed inverted one.
  5221. */
  5222. Matrix.Invert = function (source) {
  5223. var result = new Matrix();
  5224. source.invertToRef(result);
  5225. return result;
  5226. };
  5227. /**
  5228. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5229. */
  5230. Matrix.RotationXToRef = function (angle, result) {
  5231. var s = Math.sin(angle);
  5232. var c = Math.cos(angle);
  5233. result.m[0] = 1.0;
  5234. result.m[15] = 1.0;
  5235. result.m[5] = c;
  5236. result.m[10] = c;
  5237. result.m[9] = -s;
  5238. result.m[6] = s;
  5239. result.m[1] = 0.0;
  5240. result.m[2] = 0.0;
  5241. result.m[3] = 0.0;
  5242. result.m[4] = 0.0;
  5243. result.m[7] = 0.0;
  5244. result.m[8] = 0.0;
  5245. result.m[11] = 0.0;
  5246. result.m[12] = 0.0;
  5247. result.m[13] = 0.0;
  5248. result.m[14] = 0.0;
  5249. result._markAsUpdated();
  5250. };
  5251. /**
  5252. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5253. */
  5254. Matrix.RotationY = function (angle) {
  5255. var result = new Matrix();
  5256. Matrix.RotationYToRef(angle, result);
  5257. return result;
  5258. };
  5259. /**
  5260. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5261. */
  5262. Matrix.RotationYToRef = function (angle, result) {
  5263. var s = Math.sin(angle);
  5264. var c = Math.cos(angle);
  5265. result.m[5] = 1.0;
  5266. result.m[15] = 1.0;
  5267. result.m[0] = c;
  5268. result.m[2] = -s;
  5269. result.m[8] = s;
  5270. result.m[10] = c;
  5271. result.m[1] = 0.0;
  5272. result.m[3] = 0.0;
  5273. result.m[4] = 0.0;
  5274. result.m[6] = 0.0;
  5275. result.m[7] = 0.0;
  5276. result.m[9] = 0.0;
  5277. result.m[11] = 0.0;
  5278. result.m[12] = 0.0;
  5279. result.m[13] = 0.0;
  5280. result.m[14] = 0.0;
  5281. result._markAsUpdated();
  5282. };
  5283. /**
  5284. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5285. */
  5286. Matrix.RotationZ = function (angle) {
  5287. var result = new Matrix();
  5288. Matrix.RotationZToRef(angle, result);
  5289. return result;
  5290. };
  5291. /**
  5292. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5293. */
  5294. Matrix.RotationZToRef = function (angle, result) {
  5295. var s = Math.sin(angle);
  5296. var c = Math.cos(angle);
  5297. result.m[10] = 1.0;
  5298. result.m[15] = 1.0;
  5299. result.m[0] = c;
  5300. result.m[1] = s;
  5301. result.m[4] = -s;
  5302. result.m[5] = c;
  5303. result.m[2] = 0.0;
  5304. result.m[3] = 0.0;
  5305. result.m[6] = 0.0;
  5306. result.m[7] = 0.0;
  5307. result.m[8] = 0.0;
  5308. result.m[9] = 0.0;
  5309. result.m[11] = 0.0;
  5310. result.m[12] = 0.0;
  5311. result.m[13] = 0.0;
  5312. result.m[14] = 0.0;
  5313. result._markAsUpdated();
  5314. };
  5315. /**
  5316. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5317. */
  5318. Matrix.RotationAxis = function (axis, angle) {
  5319. var result = Matrix.Zero();
  5320. Matrix.RotationAxisToRef(axis, angle, result);
  5321. return result;
  5322. };
  5323. /**
  5324. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5325. */
  5326. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5327. var s = Math.sin(-angle);
  5328. var c = Math.cos(-angle);
  5329. var c1 = 1 - c;
  5330. axis.normalize();
  5331. result.m[0] = (axis.x * axis.x) * c1 + c;
  5332. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5333. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5334. result.m[3] = 0.0;
  5335. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5336. result.m[5] = (axis.y * axis.y) * c1 + c;
  5337. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5338. result.m[7] = 0.0;
  5339. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5340. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5341. result.m[10] = (axis.z * axis.z) * c1 + c;
  5342. result.m[11] = 0.0;
  5343. result.m[15] = 1.0;
  5344. result._markAsUpdated();
  5345. };
  5346. /**
  5347. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5348. */
  5349. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5350. var result = new Matrix();
  5351. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5352. return result;
  5353. };
  5354. /**
  5355. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5356. */
  5357. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5358. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5359. this._tempQuaternion.toRotationMatrix(result);
  5360. };
  5361. /**
  5362. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5363. */
  5364. Matrix.Scaling = function (x, y, z) {
  5365. var result = Matrix.Zero();
  5366. Matrix.ScalingToRef(x, y, z, result);
  5367. return result;
  5368. };
  5369. /**
  5370. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5371. */
  5372. Matrix.ScalingToRef = function (x, y, z, result) {
  5373. result.m[0] = x;
  5374. result.m[1] = 0.0;
  5375. result.m[2] = 0.0;
  5376. result.m[3] = 0.0;
  5377. result.m[4] = 0.0;
  5378. result.m[5] = y;
  5379. result.m[6] = 0.0;
  5380. result.m[7] = 0.0;
  5381. result.m[8] = 0.0;
  5382. result.m[9] = 0.0;
  5383. result.m[10] = z;
  5384. result.m[11] = 0.0;
  5385. result.m[12] = 0.0;
  5386. result.m[13] = 0.0;
  5387. result.m[14] = 0.0;
  5388. result.m[15] = 1.0;
  5389. result._markAsUpdated();
  5390. };
  5391. /**
  5392. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5393. */
  5394. Matrix.Translation = function (x, y, z) {
  5395. var result = Matrix.Identity();
  5396. Matrix.TranslationToRef(x, y, z, result);
  5397. return result;
  5398. };
  5399. /**
  5400. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5401. */
  5402. Matrix.TranslationToRef = function (x, y, z, result) {
  5403. 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);
  5404. };
  5405. /**
  5406. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5407. * @param startValue defines the start value
  5408. * @param endValue defines the end value
  5409. * @param gradient defines the gradient factor
  5410. * @returns the new matrix
  5411. */
  5412. Matrix.Lerp = function (startValue, endValue, gradient) {
  5413. var result = Matrix.Zero();
  5414. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5415. return result;
  5416. };
  5417. /**
  5418. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5419. * @param startValue defines the start value
  5420. * @param endValue defines the end value
  5421. * @param gradient defines the gradient factor
  5422. * @param result defines the Matrix object where to store data
  5423. */
  5424. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5425. for (var index = 0; index < 16; index++) {
  5426. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5427. }
  5428. result._markAsUpdated();
  5429. };
  5430. /**
  5431. * Returns a new Matrix whose values are computed by :
  5432. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5433. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5434. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5435. */
  5436. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5437. var startScale = new Vector3(0, 0, 0);
  5438. var startRotation = new Quaternion();
  5439. var startTranslation = new Vector3(0, 0, 0);
  5440. startValue.decompose(startScale, startRotation, startTranslation);
  5441. var endScale = new Vector3(0, 0, 0);
  5442. var endRotation = new Quaternion();
  5443. var endTranslation = new Vector3(0, 0, 0);
  5444. endValue.decompose(endScale, endRotation, endTranslation);
  5445. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5446. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5447. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5448. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5449. };
  5450. /**
  5451. * 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".
  5452. * This methods works for a Left-Handed system.
  5453. */
  5454. Matrix.LookAtLH = function (eye, target, up) {
  5455. var result = Matrix.Zero();
  5456. Matrix.LookAtLHToRef(eye, target, up, result);
  5457. return result;
  5458. };
  5459. /**
  5460. * 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".
  5461. * This methods works for a Left-Handed system.
  5462. */
  5463. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5464. // Z axis
  5465. target.subtractToRef(eye, this._zAxis);
  5466. this._zAxis.normalize();
  5467. // X axis
  5468. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5469. if (this._xAxis.lengthSquared() === 0) {
  5470. this._xAxis.x = 1.0;
  5471. }
  5472. else {
  5473. this._xAxis.normalize();
  5474. }
  5475. // Y axis
  5476. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5477. this._yAxis.normalize();
  5478. // Eye angles
  5479. var ex = -Vector3.Dot(this._xAxis, eye);
  5480. var ey = -Vector3.Dot(this._yAxis, eye);
  5481. var ez = -Vector3.Dot(this._zAxis, eye);
  5482. 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);
  5483. };
  5484. /**
  5485. * 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".
  5486. * This methods works for a Right-Handed system.
  5487. */
  5488. Matrix.LookAtRH = function (eye, target, up) {
  5489. var result = Matrix.Zero();
  5490. Matrix.LookAtRHToRef(eye, target, up, result);
  5491. return result;
  5492. };
  5493. /**
  5494. * 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".
  5495. * This methods works for a Left-Handed system.
  5496. */
  5497. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5498. // Z axis
  5499. eye.subtractToRef(target, this._zAxis);
  5500. this._zAxis.normalize();
  5501. // X axis
  5502. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5503. if (this._xAxis.lengthSquared() === 0) {
  5504. this._xAxis.x = 1.0;
  5505. }
  5506. else {
  5507. this._xAxis.normalize();
  5508. }
  5509. // Y axis
  5510. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5511. this._yAxis.normalize();
  5512. // Eye angles
  5513. var ex = -Vector3.Dot(this._xAxis, eye);
  5514. var ey = -Vector3.Dot(this._yAxis, eye);
  5515. var ez = -Vector3.Dot(this._zAxis, eye);
  5516. 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);
  5517. };
  5518. /**
  5519. * 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.
  5520. */
  5521. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5522. var matrix = Matrix.Zero();
  5523. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5524. return matrix;
  5525. };
  5526. /**
  5527. * 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.
  5528. */
  5529. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5530. var n = znear;
  5531. var f = zfar;
  5532. var a = 2.0 / width;
  5533. var b = 2.0 / height;
  5534. var c = 2.0 / (f - n);
  5535. var d = -(f + n) / (f - n);
  5536. 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);
  5537. };
  5538. /**
  5539. * 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.
  5540. */
  5541. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5542. var matrix = Matrix.Zero();
  5543. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5544. return matrix;
  5545. };
  5546. /**
  5547. * 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.
  5548. */
  5549. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5550. var n = znear;
  5551. var f = zfar;
  5552. var a = 2.0 / (right - left);
  5553. var b = 2.0 / (top - bottom);
  5554. var c = 2.0 / (f - n);
  5555. var d = -(f + n) / (f - n);
  5556. var i0 = (left + right) / (left - right);
  5557. var i1 = (top + bottom) / (bottom - top);
  5558. 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);
  5559. };
  5560. /**
  5561. * 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.
  5562. */
  5563. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5564. var matrix = Matrix.Zero();
  5565. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5566. return matrix;
  5567. };
  5568. /**
  5569. * 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.
  5570. */
  5571. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5572. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5573. result.m[10] *= -1.0;
  5574. };
  5575. /**
  5576. * 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.
  5577. */
  5578. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5579. var matrix = Matrix.Zero();
  5580. var n = znear;
  5581. var f = zfar;
  5582. var a = 2.0 * n / width;
  5583. var b = 2.0 * n / height;
  5584. var c = (f + n) / (f - n);
  5585. var d = -2.0 * f * n / (f - n);
  5586. 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);
  5587. return matrix;
  5588. };
  5589. /**
  5590. * 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.
  5591. */
  5592. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5593. var matrix = Matrix.Zero();
  5594. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5595. return matrix;
  5596. };
  5597. /**
  5598. * 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.
  5599. */
  5600. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5601. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5602. var n = znear;
  5603. var f = zfar;
  5604. var t = 1.0 / (Math.tan(fov * 0.5));
  5605. var a = isVerticalFovFixed ? (t / aspect) : t;
  5606. var b = isVerticalFovFixed ? t : (t * aspect);
  5607. var c = (f + n) / (f - n);
  5608. var d = -2.0 * f * n / (f - n);
  5609. 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);
  5610. };
  5611. /**
  5612. * 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.
  5613. */
  5614. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5615. var matrix = Matrix.Zero();
  5616. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5617. return matrix;
  5618. };
  5619. /**
  5620. * 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.
  5621. */
  5622. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5623. //alternatively this could be expressed as:
  5624. // m = PerspectiveFovLHToRef
  5625. // m[10] *= -1.0;
  5626. // m[11] *= -1.0;
  5627. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5628. var n = znear;
  5629. var f = zfar;
  5630. var t = 1.0 / (Math.tan(fov * 0.5));
  5631. var a = isVerticalFovFixed ? (t / aspect) : t;
  5632. var b = isVerticalFovFixed ? t : (t * aspect);
  5633. var c = -(f + n) / (f - n);
  5634. var d = -2 * f * n / (f - n);
  5635. 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);
  5636. };
  5637. /**
  5638. * 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.
  5639. */
  5640. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5641. if (rightHanded === void 0) { rightHanded = false; }
  5642. var rightHandedFactor = rightHanded ? -1 : 1;
  5643. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5644. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5645. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5646. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5647. var xScale = 2.0 / (leftTan + rightTan);
  5648. var yScale = 2.0 / (upTan + downTan);
  5649. result.m[0] = xScale;
  5650. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5651. result.m[5] = yScale;
  5652. result.m[6] = result.m[7] = 0.0;
  5653. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5654. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5655. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5656. result.m[10] = -zfar / (znear - zfar);
  5657. result.m[11] = 1.0 * rightHandedFactor;
  5658. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5659. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5660. // result.m[14] = (znear * zfar) / (znear - zfar);
  5661. result._markAsUpdated();
  5662. };
  5663. /**
  5664. * Returns the final transformation matrix : world * view * projection * viewport
  5665. */
  5666. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5667. var cw = viewport.width;
  5668. var ch = viewport.height;
  5669. var cx = viewport.x;
  5670. var cy = viewport.y;
  5671. 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);
  5672. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5673. };
  5674. /**
  5675. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5676. */
  5677. Matrix.GetAsMatrix2x2 = function (matrix) {
  5678. return new Float32Array([
  5679. matrix.m[0], matrix.m[1],
  5680. matrix.m[4], matrix.m[5]
  5681. ]);
  5682. };
  5683. /**
  5684. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5685. */
  5686. Matrix.GetAsMatrix3x3 = function (matrix) {
  5687. return new Float32Array([
  5688. matrix.m[0], matrix.m[1], matrix.m[2],
  5689. matrix.m[4], matrix.m[5], matrix.m[6],
  5690. matrix.m[8], matrix.m[9], matrix.m[10]
  5691. ]);
  5692. };
  5693. /**
  5694. * Compute the transpose of the passed Matrix.
  5695. * Returns a new Matrix.
  5696. */
  5697. Matrix.Transpose = function (matrix) {
  5698. var result = new Matrix();
  5699. Matrix.TransposeToRef(matrix, result);
  5700. return result;
  5701. };
  5702. /**
  5703. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5704. */
  5705. Matrix.TransposeToRef = function (matrix, result) {
  5706. result.m[0] = matrix.m[0];
  5707. result.m[1] = matrix.m[4];
  5708. result.m[2] = matrix.m[8];
  5709. result.m[3] = matrix.m[12];
  5710. result.m[4] = matrix.m[1];
  5711. result.m[5] = matrix.m[5];
  5712. result.m[6] = matrix.m[9];
  5713. result.m[7] = matrix.m[13];
  5714. result.m[8] = matrix.m[2];
  5715. result.m[9] = matrix.m[6];
  5716. result.m[10] = matrix.m[10];
  5717. result.m[11] = matrix.m[14];
  5718. result.m[12] = matrix.m[3];
  5719. result.m[13] = matrix.m[7];
  5720. result.m[14] = matrix.m[11];
  5721. result.m[15] = matrix.m[15];
  5722. };
  5723. /**
  5724. * Returns a new Matrix as the reflection matrix across the passed plane.
  5725. */
  5726. Matrix.Reflection = function (plane) {
  5727. var matrix = new Matrix();
  5728. Matrix.ReflectionToRef(plane, matrix);
  5729. return matrix;
  5730. };
  5731. /**
  5732. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5733. */
  5734. Matrix.ReflectionToRef = function (plane, result) {
  5735. plane.normalize();
  5736. var x = plane.normal.x;
  5737. var y = plane.normal.y;
  5738. var z = plane.normal.z;
  5739. var temp = -2 * x;
  5740. var temp2 = -2 * y;
  5741. var temp3 = -2 * z;
  5742. result.m[0] = (temp * x) + 1;
  5743. result.m[1] = temp2 * x;
  5744. result.m[2] = temp3 * x;
  5745. result.m[3] = 0.0;
  5746. result.m[4] = temp * y;
  5747. result.m[5] = (temp2 * y) + 1;
  5748. result.m[6] = temp3 * y;
  5749. result.m[7] = 0.0;
  5750. result.m[8] = temp * z;
  5751. result.m[9] = temp2 * z;
  5752. result.m[10] = (temp3 * z) + 1;
  5753. result.m[11] = 0.0;
  5754. result.m[12] = temp * plane.d;
  5755. result.m[13] = temp2 * plane.d;
  5756. result.m[14] = temp3 * plane.d;
  5757. result.m[15] = 1.0;
  5758. result._markAsUpdated();
  5759. };
  5760. /**
  5761. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5762. */
  5763. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5764. result.m[0] = xaxis.x;
  5765. result.m[1] = xaxis.y;
  5766. result.m[2] = xaxis.z;
  5767. result.m[3] = 0.0;
  5768. result.m[4] = yaxis.x;
  5769. result.m[5] = yaxis.y;
  5770. result.m[6] = yaxis.z;
  5771. result.m[7] = 0.0;
  5772. result.m[8] = zaxis.x;
  5773. result.m[9] = zaxis.y;
  5774. result.m[10] = zaxis.z;
  5775. result.m[11] = 0.0;
  5776. result.m[12] = 0.0;
  5777. result.m[13] = 0.0;
  5778. result.m[14] = 0.0;
  5779. result.m[15] = 1.0;
  5780. result._markAsUpdated();
  5781. };
  5782. /**
  5783. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5784. */
  5785. Matrix.FromQuaternionToRef = function (quat, result) {
  5786. var xx = quat.x * quat.x;
  5787. var yy = quat.y * quat.y;
  5788. var zz = quat.z * quat.z;
  5789. var xy = quat.x * quat.y;
  5790. var zw = quat.z * quat.w;
  5791. var zx = quat.z * quat.x;
  5792. var yw = quat.y * quat.w;
  5793. var yz = quat.y * quat.z;
  5794. var xw = quat.x * quat.w;
  5795. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5796. result.m[1] = 2.0 * (xy + zw);
  5797. result.m[2] = 2.0 * (zx - yw);
  5798. result.m[3] = 0.0;
  5799. result.m[4] = 2.0 * (xy - zw);
  5800. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5801. result.m[6] = 2.0 * (yz + xw);
  5802. result.m[7] = 0.0;
  5803. result.m[8] = 2.0 * (zx + yw);
  5804. result.m[9] = 2.0 * (yz - xw);
  5805. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5806. result.m[11] = 0.0;
  5807. result.m[12] = 0.0;
  5808. result.m[13] = 0.0;
  5809. result.m[14] = 0.0;
  5810. result.m[15] = 1.0;
  5811. result._markAsUpdated();
  5812. };
  5813. Matrix._tempQuaternion = new Quaternion();
  5814. Matrix._xAxis = Vector3.Zero();
  5815. Matrix._yAxis = Vector3.Zero();
  5816. Matrix._zAxis = Vector3.Zero();
  5817. Matrix._updateFlagSeed = 0;
  5818. Matrix._identityReadOnly = Matrix.Identity();
  5819. return Matrix;
  5820. }());
  5821. BABYLON.Matrix = Matrix;
  5822. var Plane = /** @class */ (function () {
  5823. /**
  5824. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5825. */
  5826. function Plane(a, b, c, d) {
  5827. this.normal = new Vector3(a, b, c);
  5828. this.d = d;
  5829. }
  5830. /**
  5831. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5832. */
  5833. Plane.prototype.asArray = function () {
  5834. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5835. };
  5836. // Methods
  5837. /**
  5838. * Returns a new plane copied from the current Plane.
  5839. */
  5840. Plane.prototype.clone = function () {
  5841. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5842. };
  5843. /**
  5844. * Returns the string "Plane".
  5845. */
  5846. Plane.prototype.getClassName = function () {
  5847. return "Plane";
  5848. };
  5849. /**
  5850. * Returns the Plane hash code.
  5851. */
  5852. Plane.prototype.getHashCode = function () {
  5853. var hash = this.normal.getHashCode();
  5854. hash = (hash * 397) ^ (this.d || 0);
  5855. return hash;
  5856. };
  5857. /**
  5858. * Normalize the current Plane in place.
  5859. * Returns the updated Plane.
  5860. */
  5861. Plane.prototype.normalize = function () {
  5862. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5863. var magnitude = 0.0;
  5864. if (norm !== 0) {
  5865. magnitude = 1.0 / norm;
  5866. }
  5867. this.normal.x *= magnitude;
  5868. this.normal.y *= magnitude;
  5869. this.normal.z *= magnitude;
  5870. this.d *= magnitude;
  5871. return this;
  5872. };
  5873. /**
  5874. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5875. */
  5876. Plane.prototype.transform = function (transformation) {
  5877. var transposedMatrix = Matrix.Transpose(transformation);
  5878. var x = this.normal.x;
  5879. var y = this.normal.y;
  5880. var z = this.normal.z;
  5881. var d = this.d;
  5882. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5883. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5884. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5885. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5886. return new Plane(normalX, normalY, normalZ, finalD);
  5887. };
  5888. /**
  5889. * Returns the dot product (float) of the point coordinates and the plane normal.
  5890. */
  5891. Plane.prototype.dotCoordinate = function (point) {
  5892. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5893. };
  5894. /**
  5895. * Updates the current Plane from the plane defined by the three passed points.
  5896. * Returns the updated Plane.
  5897. */
  5898. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5899. var x1 = point2.x - point1.x;
  5900. var y1 = point2.y - point1.y;
  5901. var z1 = point2.z - point1.z;
  5902. var x2 = point3.x - point1.x;
  5903. var y2 = point3.y - point1.y;
  5904. var z2 = point3.z - point1.z;
  5905. var yz = (y1 * z2) - (z1 * y2);
  5906. var xz = (z1 * x2) - (x1 * z2);
  5907. var xy = (x1 * y2) - (y1 * x2);
  5908. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5909. var invPyth;
  5910. if (pyth !== 0) {
  5911. invPyth = 1.0 / pyth;
  5912. }
  5913. else {
  5914. invPyth = 0.0;
  5915. }
  5916. this.normal.x = yz * invPyth;
  5917. this.normal.y = xz * invPyth;
  5918. this.normal.z = xy * invPyth;
  5919. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5920. return this;
  5921. };
  5922. /**
  5923. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5924. */
  5925. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5926. var dot = Vector3.Dot(this.normal, direction);
  5927. return (dot <= epsilon);
  5928. };
  5929. /**
  5930. * Returns the signed distance (float) from the passed point to the Plane.
  5931. */
  5932. Plane.prototype.signedDistanceTo = function (point) {
  5933. return Vector3.Dot(point, this.normal) + this.d;
  5934. };
  5935. // Statics
  5936. /**
  5937. * Returns a new Plane from the passed array.
  5938. */
  5939. Plane.FromArray = function (array) {
  5940. return new Plane(array[0], array[1], array[2], array[3]);
  5941. };
  5942. /**
  5943. * Returns a new Plane defined by the three passed points.
  5944. */
  5945. Plane.FromPoints = function (point1, point2, point3) {
  5946. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5947. result.copyFromPoints(point1, point2, point3);
  5948. return result;
  5949. };
  5950. /**
  5951. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5952. * Note : the vector "normal" is updated because normalized.
  5953. */
  5954. Plane.FromPositionAndNormal = function (origin, normal) {
  5955. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5956. normal.normalize();
  5957. result.normal = normal;
  5958. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5959. return result;
  5960. };
  5961. /**
  5962. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5963. */
  5964. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5965. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5966. return Vector3.Dot(point, normal) + d;
  5967. };
  5968. return Plane;
  5969. }());
  5970. BABYLON.Plane = Plane;
  5971. var Viewport = /** @class */ (function () {
  5972. /**
  5973. * Creates a Viewport object located at (x, y) and sized (width, height).
  5974. */
  5975. function Viewport(x, y, width, height) {
  5976. this.x = x;
  5977. this.y = y;
  5978. this.width = width;
  5979. this.height = height;
  5980. }
  5981. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5982. if (renderWidthOrEngine.getRenderWidth) {
  5983. var engine = renderWidthOrEngine;
  5984. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5985. }
  5986. var renderWidth = renderWidthOrEngine;
  5987. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5988. };
  5989. /**
  5990. * Returns a new Viewport copied from the current one.
  5991. */
  5992. Viewport.prototype.clone = function () {
  5993. return new Viewport(this.x, this.y, this.width, this.height);
  5994. };
  5995. return Viewport;
  5996. }());
  5997. BABYLON.Viewport = Viewport;
  5998. var Frustum = /** @class */ (function () {
  5999. function Frustum() {
  6000. }
  6001. /**
  6002. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6003. */
  6004. Frustum.GetPlanes = function (transform) {
  6005. var frustumPlanes = [];
  6006. for (var index = 0; index < 6; index++) {
  6007. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6008. }
  6009. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6010. return frustumPlanes;
  6011. };
  6012. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6013. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6014. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6015. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6016. frustumPlane.d = transform.m[15] + transform.m[14];
  6017. frustumPlane.normalize();
  6018. };
  6019. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6020. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6021. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6022. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6023. frustumPlane.d = transform.m[15] - transform.m[14];
  6024. frustumPlane.normalize();
  6025. };
  6026. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6027. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6028. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6029. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6030. frustumPlane.d = transform.m[15] + transform.m[12];
  6031. frustumPlane.normalize();
  6032. };
  6033. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6034. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6035. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6036. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6037. frustumPlane.d = transform.m[15] - transform.m[12];
  6038. frustumPlane.normalize();
  6039. };
  6040. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6041. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6042. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6043. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6044. frustumPlane.d = transform.m[15] - transform.m[13];
  6045. frustumPlane.normalize();
  6046. };
  6047. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6048. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6049. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6050. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6051. frustumPlane.d = transform.m[15] + transform.m[13];
  6052. frustumPlane.normalize();
  6053. };
  6054. /**
  6055. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6056. */
  6057. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6058. // Near
  6059. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6060. // Far
  6061. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6062. // Left
  6063. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6064. // Right
  6065. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6066. // Top
  6067. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6068. // Bottom
  6069. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6070. };
  6071. return Frustum;
  6072. }());
  6073. BABYLON.Frustum = Frustum;
  6074. var Space;
  6075. (function (Space) {
  6076. Space[Space["LOCAL"] = 0] = "LOCAL";
  6077. Space[Space["WORLD"] = 1] = "WORLD";
  6078. Space[Space["BONE"] = 2] = "BONE";
  6079. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6080. var Axis = /** @class */ (function () {
  6081. function Axis() {
  6082. }
  6083. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6084. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6085. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6086. return Axis;
  6087. }());
  6088. BABYLON.Axis = Axis;
  6089. ;
  6090. var BezierCurve = /** @class */ (function () {
  6091. function BezierCurve() {
  6092. }
  6093. /**
  6094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6095. */
  6096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6097. // Extract X (which is equal to time here)
  6098. var f0 = 1 - 3 * x2 + 3 * x1;
  6099. var f1 = 3 * x2 - 6 * x1;
  6100. var f2 = 3 * x1;
  6101. var refinedT = t;
  6102. for (var i = 0; i < 5; i++) {
  6103. var refinedT2 = refinedT * refinedT;
  6104. var refinedT3 = refinedT2 * refinedT;
  6105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6107. refinedT -= (x - t) * slope;
  6108. refinedT = Math.min(1, Math.max(0, refinedT));
  6109. }
  6110. // Resolve cubic bezier for the given x
  6111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6113. Math.pow(refinedT, 3);
  6114. };
  6115. return BezierCurve;
  6116. }());
  6117. BABYLON.BezierCurve = BezierCurve;
  6118. var Orientation;
  6119. (function (Orientation) {
  6120. Orientation[Orientation["CW"] = 0] = "CW";
  6121. Orientation[Orientation["CCW"] = 1] = "CCW";
  6122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6123. var Angle = /** @class */ (function () {
  6124. /**
  6125. * Creates an Angle object of "radians" radians (float).
  6126. */
  6127. function Angle(radians) {
  6128. var _this = this;
  6129. /**
  6130. * Returns the Angle value in degrees (float).
  6131. */
  6132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6133. /**
  6134. * Returns the Angle value in radians (float).
  6135. */
  6136. this.radians = function () { return _this._radians; };
  6137. this._radians = radians;
  6138. if (this._radians < 0.0)
  6139. this._radians += (2.0 * Math.PI);
  6140. }
  6141. /**
  6142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6143. */
  6144. Angle.BetweenTwoPoints = function (a, b) {
  6145. var delta = b.subtract(a);
  6146. var theta = Math.atan2(delta.y, delta.x);
  6147. return new Angle(theta);
  6148. };
  6149. /**
  6150. * Returns a new Angle object from the passed float in radians.
  6151. */
  6152. Angle.FromRadians = function (radians) {
  6153. return new Angle(radians);
  6154. };
  6155. /**
  6156. * Returns a new Angle object from the passed float in degrees.
  6157. */
  6158. Angle.FromDegrees = function (degrees) {
  6159. return new Angle(degrees * Math.PI / 180.0);
  6160. };
  6161. return Angle;
  6162. }());
  6163. BABYLON.Angle = Angle;
  6164. var Arc2 = /** @class */ (function () {
  6165. /**
  6166. * Creates an Arc object from the three passed points : start, middle and end.
  6167. */
  6168. function Arc2(startPoint, midPoint, endPoint) {
  6169. this.startPoint = startPoint;
  6170. this.midPoint = midPoint;
  6171. this.endPoint = endPoint;
  6172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6176. 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);
  6177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6179. var a1 = this.startAngle.degrees();
  6180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6182. // angles correction
  6183. if (a2 - a1 > +180.0)
  6184. a2 -= 360.0;
  6185. if (a2 - a1 < -180.0)
  6186. a2 += 360.0;
  6187. if (a3 - a2 > +180.0)
  6188. a3 -= 360.0;
  6189. if (a3 - a2 < -180.0)
  6190. a3 += 360.0;
  6191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6193. }
  6194. return Arc2;
  6195. }());
  6196. BABYLON.Arc2 = Arc2;
  6197. var Path2 = /** @class */ (function () {
  6198. /**
  6199. * Creates a Path2 object from the starting 2D coordinates x and y.
  6200. */
  6201. function Path2(x, y) {
  6202. this._points = new Array();
  6203. this._length = 0.0;
  6204. this.closed = false;
  6205. this._points.push(new Vector2(x, y));
  6206. }
  6207. /**
  6208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6209. * Returns the updated Path2.
  6210. */
  6211. Path2.prototype.addLineTo = function (x, y) {
  6212. if (this.closed) {
  6213. return this;
  6214. }
  6215. var newPoint = new Vector2(x, y);
  6216. var previousPoint = this._points[this._points.length - 1];
  6217. this._points.push(newPoint);
  6218. this._length += newPoint.subtract(previousPoint).length();
  6219. return this;
  6220. };
  6221. /**
  6222. * 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.
  6223. * Returns the updated Path2.
  6224. */
  6225. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6226. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6227. if (this.closed) {
  6228. return this;
  6229. }
  6230. var startPoint = this._points[this._points.length - 1];
  6231. var midPoint = new Vector2(midX, midY);
  6232. var endPoint = new Vector2(endX, endY);
  6233. var arc = new Arc2(startPoint, midPoint, endPoint);
  6234. var increment = arc.angle.radians() / numberOfSegments;
  6235. if (arc.orientation === Orientation.CW)
  6236. increment *= -1;
  6237. var currentAngle = arc.startAngle.radians() + increment;
  6238. for (var i = 0; i < numberOfSegments; i++) {
  6239. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6240. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6241. this.addLineTo(x, y);
  6242. currentAngle += increment;
  6243. }
  6244. return this;
  6245. };
  6246. /**
  6247. * Closes the Path2.
  6248. * Returns the Path2.
  6249. */
  6250. Path2.prototype.close = function () {
  6251. this.closed = true;
  6252. return this;
  6253. };
  6254. /**
  6255. * Returns the Path2 total length (float).
  6256. */
  6257. Path2.prototype.length = function () {
  6258. var result = this._length;
  6259. if (!this.closed) {
  6260. var lastPoint = this._points[this._points.length - 1];
  6261. var firstPoint = this._points[0];
  6262. result += (firstPoint.subtract(lastPoint).length());
  6263. }
  6264. return result;
  6265. };
  6266. /**
  6267. * Returns the Path2 internal array of points.
  6268. */
  6269. Path2.prototype.getPoints = function () {
  6270. return this._points;
  6271. };
  6272. /**
  6273. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6274. */
  6275. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6276. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6277. return Vector2.Zero();
  6278. }
  6279. var lengthPosition = normalizedLengthPosition * this.length();
  6280. var previousOffset = 0;
  6281. for (var i = 0; i < this._points.length; i++) {
  6282. var j = (i + 1) % this._points.length;
  6283. var a = this._points[i];
  6284. var b = this._points[j];
  6285. var bToA = b.subtract(a);
  6286. var nextOffset = (bToA.length() + previousOffset);
  6287. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6288. var dir = bToA.normalize();
  6289. var localOffset = lengthPosition - previousOffset;
  6290. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6291. }
  6292. previousOffset = nextOffset;
  6293. }
  6294. return Vector2.Zero();
  6295. };
  6296. /**
  6297. * Returns a new Path2 starting at the coordinates (x, y).
  6298. */
  6299. Path2.StartingAt = function (x, y) {
  6300. return new Path2(x, y);
  6301. };
  6302. return Path2;
  6303. }());
  6304. BABYLON.Path2 = Path2;
  6305. var Path3D = /** @class */ (function () {
  6306. /**
  6307. * new Path3D(path, normal, raw)
  6308. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6309. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6310. * path : an array of Vector3, the curve axis of the Path3D
  6311. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6312. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6313. */
  6314. function Path3D(path, firstNormal, raw) {
  6315. if (firstNormal === void 0) { firstNormal = null; }
  6316. this.path = path;
  6317. this._curve = new Array();
  6318. this._distances = new Array();
  6319. this._tangents = new Array();
  6320. this._normals = new Array();
  6321. this._binormals = new Array();
  6322. for (var p = 0; p < path.length; p++) {
  6323. this._curve[p] = path[p].clone(); // hard copy
  6324. }
  6325. this._raw = raw || false;
  6326. this._compute(firstNormal);
  6327. }
  6328. /**
  6329. * Returns the Path3D array of successive Vector3 designing its curve.
  6330. */
  6331. Path3D.prototype.getCurve = function () {
  6332. return this._curve;
  6333. };
  6334. /**
  6335. * Returns an array populated with tangent vectors on each Path3D curve point.
  6336. */
  6337. Path3D.prototype.getTangents = function () {
  6338. return this._tangents;
  6339. };
  6340. /**
  6341. * Returns an array populated with normal vectors on each Path3D curve point.
  6342. */
  6343. Path3D.prototype.getNormals = function () {
  6344. return this._normals;
  6345. };
  6346. /**
  6347. * Returns an array populated with binormal vectors on each Path3D curve point.
  6348. */
  6349. Path3D.prototype.getBinormals = function () {
  6350. return this._binormals;
  6351. };
  6352. /**
  6353. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6354. */
  6355. Path3D.prototype.getDistances = function () {
  6356. return this._distances;
  6357. };
  6358. /**
  6359. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6360. * Returns the same object updated.
  6361. */
  6362. Path3D.prototype.update = function (path, firstNormal) {
  6363. if (firstNormal === void 0) { firstNormal = null; }
  6364. for (var p = 0; p < path.length; p++) {
  6365. this._curve[p].x = path[p].x;
  6366. this._curve[p].y = path[p].y;
  6367. this._curve[p].z = path[p].z;
  6368. }
  6369. this._compute(firstNormal);
  6370. return this;
  6371. };
  6372. // private function compute() : computes tangents, normals and binormals
  6373. Path3D.prototype._compute = function (firstNormal) {
  6374. var l = this._curve.length;
  6375. // first and last tangents
  6376. this._tangents[0] = this._getFirstNonNullVector(0);
  6377. if (!this._raw) {
  6378. this._tangents[0].normalize();
  6379. }
  6380. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6381. if (!this._raw) {
  6382. this._tangents[l - 1].normalize();
  6383. }
  6384. // normals and binormals at first point : arbitrary vector with _normalVector()
  6385. var tg0 = this._tangents[0];
  6386. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6387. this._normals[0] = pp0;
  6388. if (!this._raw) {
  6389. this._normals[0].normalize();
  6390. }
  6391. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6392. if (!this._raw) {
  6393. this._binormals[0].normalize();
  6394. }
  6395. this._distances[0] = 0.0;
  6396. // normals and binormals : next points
  6397. var prev; // previous vector (segment)
  6398. var cur; // current vector (segment)
  6399. var curTang; // current tangent
  6400. // previous normal
  6401. var prevBinor; // previous binormal
  6402. for (var i = 1; i < l; i++) {
  6403. // tangents
  6404. prev = this._getLastNonNullVector(i);
  6405. if (i < l - 1) {
  6406. cur = this._getFirstNonNullVector(i);
  6407. this._tangents[i] = prev.add(cur);
  6408. this._tangents[i].normalize();
  6409. }
  6410. this._distances[i] = this._distances[i - 1] + prev.length();
  6411. // normals and binormals
  6412. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6413. curTang = this._tangents[i];
  6414. prevBinor = this._binormals[i - 1];
  6415. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6416. if (!this._raw) {
  6417. this._normals[i].normalize();
  6418. }
  6419. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6420. if (!this._raw) {
  6421. this._binormals[i].normalize();
  6422. }
  6423. }
  6424. };
  6425. // private function getFirstNonNullVector(index)
  6426. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6427. Path3D.prototype._getFirstNonNullVector = function (index) {
  6428. var i = 1;
  6429. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6430. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6431. i++;
  6432. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6433. }
  6434. return nNVector;
  6435. };
  6436. // private function getLastNonNullVector(index)
  6437. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6438. Path3D.prototype._getLastNonNullVector = function (index) {
  6439. var i = 1;
  6440. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6441. while (nLVector.length() === 0 && index > i + 1) {
  6442. i++;
  6443. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6444. }
  6445. return nLVector;
  6446. };
  6447. // private function normalVector(v0, vt, va) :
  6448. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6449. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6450. Path3D.prototype._normalVector = function (v0, vt, va) {
  6451. var normal0;
  6452. var tgl = vt.length();
  6453. if (tgl === 0.0) {
  6454. tgl = 1.0;
  6455. }
  6456. if (va === undefined || va === null) {
  6457. var point;
  6458. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6459. point = new Vector3(0.0, -1.0, 0.0);
  6460. }
  6461. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6462. point = new Vector3(1.0, 0.0, 0.0);
  6463. }
  6464. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6465. point = new Vector3(0.0, 0.0, 1.0);
  6466. }
  6467. else {
  6468. point = Vector3.Zero();
  6469. }
  6470. normal0 = Vector3.Cross(vt, point);
  6471. }
  6472. else {
  6473. normal0 = Vector3.Cross(vt, va);
  6474. Vector3.CrossToRef(normal0, vt, normal0);
  6475. }
  6476. normal0.normalize();
  6477. return normal0;
  6478. };
  6479. return Path3D;
  6480. }());
  6481. BABYLON.Path3D = Path3D;
  6482. var Curve3 = /** @class */ (function () {
  6483. /**
  6484. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6485. * A Curve3 is designed from a series of successive Vector3.
  6486. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6487. */
  6488. function Curve3(points) {
  6489. this._length = 0.0;
  6490. this._points = points;
  6491. this._length = this._computeLength(points);
  6492. }
  6493. /**
  6494. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6495. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6496. * @param v1 (Vector3) the control point
  6497. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6498. * @param nbPoints (integer) the wanted number of points in the curve
  6499. */
  6500. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6501. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6502. var bez = new Array();
  6503. var equation = function (t, val0, val1, val2) {
  6504. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6505. return res;
  6506. };
  6507. for (var i = 0; i <= nbPoints; i++) {
  6508. 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)));
  6509. }
  6510. return new Curve3(bez);
  6511. };
  6512. /**
  6513. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6514. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6515. * @param v1 (Vector3) the first control point
  6516. * @param v2 (Vector3) the second control point
  6517. * @param v3 (Vector3) the end point of the Cubic Bezier
  6518. * @param nbPoints (integer) the wanted number of points in the curve
  6519. */
  6520. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6521. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6522. var bez = new Array();
  6523. var equation = function (t, val0, val1, val2, val3) {
  6524. 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;
  6525. return res;
  6526. };
  6527. for (var i = 0; i <= nbPoints; i++) {
  6528. 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)));
  6529. }
  6530. return new Curve3(bez);
  6531. };
  6532. /**
  6533. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6534. * @param p1 (Vector3) the origin point of the Hermite Spline
  6535. * @param t1 (Vector3) the tangent vector at the origin point
  6536. * @param p2 (Vector3) the end point of the Hermite Spline
  6537. * @param t2 (Vector3) the tangent vector at the end point
  6538. * @param nbPoints (integer) the wanted number of points in the curve
  6539. */
  6540. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6541. var hermite = new Array();
  6542. var step = 1.0 / nbPoints;
  6543. for (var i = 0; i <= nbPoints; i++) {
  6544. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6545. }
  6546. return new Curve3(hermite);
  6547. };
  6548. /**
  6549. * Returns a Curve3 object along a CatmullRom Spline curve :
  6550. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6551. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6552. */
  6553. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6554. var totalPoints = new Array();
  6555. totalPoints.push(points[0].clone());
  6556. Array.prototype.push.apply(totalPoints, points);
  6557. totalPoints.push(points[points.length - 1].clone());
  6558. var catmullRom = new Array();
  6559. var step = 1.0 / nbPoints;
  6560. var amount = 0.0;
  6561. for (var i = 0; i < totalPoints.length - 3; i++) {
  6562. amount = 0;
  6563. for (var c = 0; c < nbPoints; c++) {
  6564. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6565. amount += step;
  6566. }
  6567. }
  6568. i--;
  6569. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6570. return new Curve3(catmullRom);
  6571. };
  6572. /**
  6573. * Returns the Curve3 stored array of successive Vector3
  6574. */
  6575. Curve3.prototype.getPoints = function () {
  6576. return this._points;
  6577. };
  6578. /**
  6579. * Returns the computed length (float) of the curve.
  6580. */
  6581. Curve3.prototype.length = function () {
  6582. return this._length;
  6583. };
  6584. /**
  6585. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6586. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6587. * curveA and curveB keep unchanged.
  6588. */
  6589. Curve3.prototype.continue = function (curve) {
  6590. var lastPoint = this._points[this._points.length - 1];
  6591. var continuedPoints = this._points.slice();
  6592. var curvePoints = curve.getPoints();
  6593. for (var i = 1; i < curvePoints.length; i++) {
  6594. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6595. }
  6596. var continuedCurve = new Curve3(continuedPoints);
  6597. return continuedCurve;
  6598. };
  6599. Curve3.prototype._computeLength = function (path) {
  6600. var l = 0;
  6601. for (var i = 1; i < path.length; i++) {
  6602. l += (path[i].subtract(path[i - 1])).length();
  6603. }
  6604. return l;
  6605. };
  6606. return Curve3;
  6607. }());
  6608. BABYLON.Curve3 = Curve3;
  6609. // Vertex formats
  6610. var PositionNormalVertex = /** @class */ (function () {
  6611. function PositionNormalVertex(position, normal) {
  6612. if (position === void 0) { position = Vector3.Zero(); }
  6613. if (normal === void 0) { normal = Vector3.Up(); }
  6614. this.position = position;
  6615. this.normal = normal;
  6616. }
  6617. PositionNormalVertex.prototype.clone = function () {
  6618. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6619. };
  6620. return PositionNormalVertex;
  6621. }());
  6622. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6623. var PositionNormalTextureVertex = /** @class */ (function () {
  6624. function PositionNormalTextureVertex(position, normal, uv) {
  6625. if (position === void 0) { position = Vector3.Zero(); }
  6626. if (normal === void 0) { normal = Vector3.Up(); }
  6627. if (uv === void 0) { uv = Vector2.Zero(); }
  6628. this.position = position;
  6629. this.normal = normal;
  6630. this.uv = uv;
  6631. }
  6632. PositionNormalTextureVertex.prototype.clone = function () {
  6633. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6634. };
  6635. return PositionNormalTextureVertex;
  6636. }());
  6637. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6638. // Temporary pre-allocated objects for engine internal use
  6639. // usage in any internal function :
  6640. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6641. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6642. var Tmp = /** @class */ (function () {
  6643. function Tmp() {
  6644. }
  6645. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6646. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6647. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6648. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6649. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6650. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6651. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6652. Matrix.Zero(), Matrix.Zero(),
  6653. Matrix.Zero(), Matrix.Zero(),
  6654. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6655. return Tmp;
  6656. }());
  6657. BABYLON.Tmp = Tmp;
  6658. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6659. var MathTmp = /** @class */ (function () {
  6660. function MathTmp() {
  6661. }
  6662. MathTmp.Vector3 = [Vector3.Zero()];
  6663. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6664. MathTmp.Quaternion = [Quaternion.Zero()];
  6665. return MathTmp;
  6666. }());
  6667. })(BABYLON || (BABYLON = {}));
  6668. //# sourceMappingURL=babylon.math.js.map
  6669. var BABYLON;
  6670. (function (BABYLON) {
  6671. var Scalar = /** @class */ (function () {
  6672. function Scalar() {
  6673. }
  6674. /**
  6675. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6676. */
  6677. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6678. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6679. var num = a - b;
  6680. return -epsilon <= num && num <= epsilon;
  6681. };
  6682. /**
  6683. * Returns a string : the upper case translation of the number i to hexadecimal.
  6684. */
  6685. Scalar.ToHex = function (i) {
  6686. var str = i.toString(16);
  6687. if (i <= 15) {
  6688. return ("0" + str).toUpperCase();
  6689. }
  6690. return str.toUpperCase();
  6691. };
  6692. /**
  6693. * Returns -1 if value is negative and +1 is value is positive.
  6694. * Returns the value itself if it's equal to zero.
  6695. */
  6696. Scalar.Sign = function (value) {
  6697. value = +value; // convert to a number
  6698. if (value === 0 || isNaN(value))
  6699. return value;
  6700. return value > 0 ? 1 : -1;
  6701. };
  6702. /**
  6703. * Returns the value itself if it's between min and max.
  6704. * Returns min if the value is lower than min.
  6705. * Returns max if the value is greater than max.
  6706. */
  6707. Scalar.Clamp = function (value, min, max) {
  6708. if (min === void 0) { min = 0; }
  6709. if (max === void 0) { max = 1; }
  6710. return Math.min(max, Math.max(min, value));
  6711. };
  6712. /**
  6713. * Returns the log2 of value.
  6714. */
  6715. Scalar.Log2 = function (value) {
  6716. return Math.log(value) * Math.LOG2E;
  6717. };
  6718. /**
  6719. * Loops the value, so that it is never larger than length and never smaller than 0.
  6720. *
  6721. * This is similar to the modulo operator but it works with floating point numbers.
  6722. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6723. * With t = 5 and length = 2.5, the result would be 0.0.
  6724. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6725. */
  6726. Scalar.Repeat = function (value, length) {
  6727. return value - Math.floor(value / length) * length;
  6728. };
  6729. /**
  6730. * Normalize the value between 0.0 and 1.0 using min and max values
  6731. */
  6732. Scalar.Normalize = function (value, min, max) {
  6733. return (value - min) / (max - min);
  6734. };
  6735. /**
  6736. * Denormalize the value from 0.0 and 1.0 using min and max values
  6737. */
  6738. Scalar.Denormalize = function (normalized, min, max) {
  6739. return (normalized * (max - min) + min);
  6740. };
  6741. /**
  6742. * Calculates the shortest difference between two given angles given in degrees.
  6743. */
  6744. Scalar.DeltaAngle = function (current, target) {
  6745. var num = Scalar.Repeat(target - current, 360.0);
  6746. if (num > 180.0) {
  6747. num -= 360.0;
  6748. }
  6749. return num;
  6750. };
  6751. /**
  6752. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6753. *
  6754. * The returned value will move back and forth between 0 and length
  6755. */
  6756. Scalar.PingPong = function (tx, length) {
  6757. var t = Scalar.Repeat(tx, length * 2.0);
  6758. return length - Math.abs(t - length);
  6759. };
  6760. /**
  6761. * Interpolates between min and max with smoothing at the limits.
  6762. *
  6763. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6764. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6765. */
  6766. Scalar.SmoothStep = function (from, to, tx) {
  6767. var t = Scalar.Clamp(tx);
  6768. t = -2.0 * t * t * t + 3.0 * t * t;
  6769. return to * t + from * (1.0 - t);
  6770. };
  6771. /**
  6772. * Moves a value current towards target.
  6773. *
  6774. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6775. * Negative values of maxDelta pushes the value away from target.
  6776. */
  6777. Scalar.MoveTowards = function (current, target, maxDelta) {
  6778. var result = 0;
  6779. if (Math.abs(target - current) <= maxDelta) {
  6780. result = target;
  6781. }
  6782. else {
  6783. result = current + Scalar.Sign(target - current) * maxDelta;
  6784. }
  6785. return result;
  6786. };
  6787. /**
  6788. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6789. *
  6790. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6791. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6792. */
  6793. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6794. var num = Scalar.DeltaAngle(current, target);
  6795. var result = 0;
  6796. if (-maxDelta < num && num < maxDelta) {
  6797. result = target;
  6798. }
  6799. else {
  6800. target = current + num;
  6801. result = Scalar.MoveTowards(current, target, maxDelta);
  6802. }
  6803. return result;
  6804. };
  6805. /**
  6806. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6807. */
  6808. Scalar.Lerp = function (start, end, amount) {
  6809. return start + ((end - start) * amount);
  6810. };
  6811. /**
  6812. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6813. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6814. */
  6815. Scalar.LerpAngle = function (start, end, amount) {
  6816. var num = Scalar.Repeat(end - start, 360.0);
  6817. if (num > 180.0) {
  6818. num -= 360.0;
  6819. }
  6820. return start + num * Scalar.Clamp(amount);
  6821. };
  6822. /**
  6823. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6824. */
  6825. Scalar.InverseLerp = function (a, b, value) {
  6826. var result = 0;
  6827. if (a != b) {
  6828. result = Scalar.Clamp((value - a) / (b - a));
  6829. }
  6830. else {
  6831. result = 0.0;
  6832. }
  6833. return result;
  6834. };
  6835. /**
  6836. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6837. */
  6838. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6839. var squared = amount * amount;
  6840. var cubed = amount * squared;
  6841. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6842. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6843. var part3 = (cubed - (2.0 * squared)) + amount;
  6844. var part4 = cubed - squared;
  6845. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6846. };
  6847. /**
  6848. * Returns a random float number between and min and max values
  6849. */
  6850. Scalar.RandomRange = function (min, max) {
  6851. if (min === max)
  6852. return min;
  6853. return ((Math.random() * (max - min)) + min);
  6854. };
  6855. /**
  6856. * This function returns percentage of a number in a given range.
  6857. *
  6858. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6859. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6860. */
  6861. Scalar.RangeToPercent = function (number, min, max) {
  6862. return ((number - min) / (max - min));
  6863. };
  6864. /**
  6865. * This function returns number that corresponds to the percentage in a given range.
  6866. *
  6867. * PercentToRange(0.34,0,100) will return 34.
  6868. */
  6869. Scalar.PercentToRange = function (percent, min, max) {
  6870. return ((max - min) * percent + min);
  6871. };
  6872. /**
  6873. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6874. * @param angle The angle to normalize in radian.
  6875. * @return The converted angle.
  6876. */
  6877. Scalar.NormalizeRadians = function (angle) {
  6878. // More precise but slower version kept for reference.
  6879. // angle = angle % Tools.TwoPi;
  6880. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6881. //if (angle > Math.PI) {
  6882. // angle -= Tools.TwoPi;
  6883. //}
  6884. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6885. return angle;
  6886. };
  6887. /**
  6888. * Two pi constants convenient for computation.
  6889. */
  6890. Scalar.TwoPi = Math.PI * 2;
  6891. return Scalar;
  6892. }());
  6893. BABYLON.Scalar = Scalar;
  6894. })(BABYLON || (BABYLON = {}));
  6895. //# sourceMappingURL=babylon.math.scalar.js.map
  6896. //# sourceMappingURL=babylon.mixins.js.map
  6897. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6898. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6899. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6900. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6901. //# sourceMappingURL=babylon.webgl2.js.map
  6902. var BABYLON;
  6903. (function (BABYLON) {
  6904. var __decoratorInitialStore = {};
  6905. var __mergedStore = {};
  6906. var _copySource = function (creationFunction, source, instanciate) {
  6907. var destination = creationFunction();
  6908. // Tags
  6909. if (BABYLON.Tags) {
  6910. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6911. }
  6912. var classStore = getMergedStore(destination);
  6913. // Properties
  6914. for (var property in classStore) {
  6915. var propertyDescriptor = classStore[property];
  6916. var sourceProperty = source[property];
  6917. var propertyType = propertyDescriptor.type;
  6918. if (sourceProperty !== undefined && sourceProperty !== null) {
  6919. switch (propertyType) {
  6920. case 0: // Value
  6921. case 6:// Mesh reference
  6922. destination[property] = sourceProperty;
  6923. break;
  6924. case 1:// Texture
  6925. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6926. break;
  6927. case 2: // Color3
  6928. case 3: // FresnelParameters
  6929. case 4: // Vector2
  6930. case 5: // Vector3
  6931. case 7: // Color Curves
  6932. case 10:// Quaternion
  6933. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6934. break;
  6935. }
  6936. }
  6937. }
  6938. return destination;
  6939. };
  6940. function getDirectStore(target) {
  6941. var classKey = target.getClassName();
  6942. if (!__decoratorInitialStore[classKey]) {
  6943. __decoratorInitialStore[classKey] = {};
  6944. }
  6945. return __decoratorInitialStore[classKey];
  6946. }
  6947. /**
  6948. * Return the list of properties flagged as serializable
  6949. * @param target: host object
  6950. */
  6951. function getMergedStore(target) {
  6952. var classKey = target.getClassName();
  6953. if (__mergedStore[classKey]) {
  6954. return __mergedStore[classKey];
  6955. }
  6956. __mergedStore[classKey] = {};
  6957. var store = __mergedStore[classKey];
  6958. var currentTarget = target;
  6959. var currentKey = classKey;
  6960. while (currentKey) {
  6961. var initialStore = __decoratorInitialStore[currentKey];
  6962. for (var property in initialStore) {
  6963. store[property] = initialStore[property];
  6964. }
  6965. var parent_1 = void 0;
  6966. var done = false;
  6967. do {
  6968. parent_1 = Object.getPrototypeOf(currentTarget);
  6969. if (!parent_1.getClassName) {
  6970. done = true;
  6971. break;
  6972. }
  6973. if (parent_1.getClassName() !== currentKey) {
  6974. break;
  6975. }
  6976. currentTarget = parent_1;
  6977. } while (parent_1);
  6978. if (done) {
  6979. break;
  6980. }
  6981. currentKey = parent_1.getClassName();
  6982. currentTarget = parent_1;
  6983. }
  6984. return store;
  6985. }
  6986. function generateSerializableMember(type, sourceName) {
  6987. return function (target, propertyKey) {
  6988. var classStore = getDirectStore(target);
  6989. if (!classStore[propertyKey]) {
  6990. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6991. }
  6992. };
  6993. }
  6994. function generateExpandMember(setCallback, targetKey) {
  6995. if (targetKey === void 0) { targetKey = null; }
  6996. return function (target, propertyKey) {
  6997. var key = targetKey || ("_" + propertyKey);
  6998. Object.defineProperty(target, propertyKey, {
  6999. get: function () {
  7000. return this[key];
  7001. },
  7002. set: function (value) {
  7003. if (this[key] === value) {
  7004. return;
  7005. }
  7006. this[key] = value;
  7007. target[setCallback].apply(this);
  7008. },
  7009. enumerable: true,
  7010. configurable: true
  7011. });
  7012. };
  7013. }
  7014. function expandToProperty(callback, targetKey) {
  7015. if (targetKey === void 0) { targetKey = null; }
  7016. return generateExpandMember(callback, targetKey);
  7017. }
  7018. BABYLON.expandToProperty = expandToProperty;
  7019. function serialize(sourceName) {
  7020. return generateSerializableMember(0, sourceName); // value member
  7021. }
  7022. BABYLON.serialize = serialize;
  7023. function serializeAsTexture(sourceName) {
  7024. return generateSerializableMember(1, sourceName); // texture member
  7025. }
  7026. BABYLON.serializeAsTexture = serializeAsTexture;
  7027. function serializeAsColor3(sourceName) {
  7028. return generateSerializableMember(2, sourceName); // color3 member
  7029. }
  7030. BABYLON.serializeAsColor3 = serializeAsColor3;
  7031. function serializeAsFresnelParameters(sourceName) {
  7032. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7033. }
  7034. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7035. function serializeAsVector2(sourceName) {
  7036. return generateSerializableMember(4, sourceName); // vector2 member
  7037. }
  7038. BABYLON.serializeAsVector2 = serializeAsVector2;
  7039. function serializeAsVector3(sourceName) {
  7040. return generateSerializableMember(5, sourceName); // vector3 member
  7041. }
  7042. BABYLON.serializeAsVector3 = serializeAsVector3;
  7043. function serializeAsMeshReference(sourceName) {
  7044. return generateSerializableMember(6, sourceName); // mesh reference member
  7045. }
  7046. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7047. function serializeAsColorCurves(sourceName) {
  7048. return generateSerializableMember(7, sourceName); // color curves
  7049. }
  7050. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7051. function serializeAsColor4(sourceName) {
  7052. return generateSerializableMember(8, sourceName); // color 4
  7053. }
  7054. BABYLON.serializeAsColor4 = serializeAsColor4;
  7055. function serializeAsImageProcessingConfiguration(sourceName) {
  7056. return generateSerializableMember(9, sourceName); // image processing
  7057. }
  7058. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7059. function serializeAsQuaternion(sourceName) {
  7060. return generateSerializableMember(10, sourceName); // quaternion member
  7061. }
  7062. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7063. var SerializationHelper = /** @class */ (function () {
  7064. function SerializationHelper() {
  7065. }
  7066. SerializationHelper.Serialize = function (entity, serializationObject) {
  7067. if (!serializationObject) {
  7068. serializationObject = {};
  7069. }
  7070. // Tags
  7071. if (BABYLON.Tags) {
  7072. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7073. }
  7074. var serializedProperties = getMergedStore(entity);
  7075. // Properties
  7076. for (var property in serializedProperties) {
  7077. var propertyDescriptor = serializedProperties[property];
  7078. var targetPropertyName = propertyDescriptor.sourceName || property;
  7079. var propertyType = propertyDescriptor.type;
  7080. var sourceProperty = entity[property];
  7081. if (sourceProperty !== undefined && sourceProperty !== null) {
  7082. switch (propertyType) {
  7083. case 0:// Value
  7084. serializationObject[targetPropertyName] = sourceProperty;
  7085. break;
  7086. case 1:// Texture
  7087. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7088. break;
  7089. case 2:// Color3
  7090. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7091. break;
  7092. case 3:// FresnelParameters
  7093. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7094. break;
  7095. case 4:// Vector2
  7096. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7097. break;
  7098. case 5:// Vector3
  7099. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7100. break;
  7101. case 6:// Mesh reference
  7102. serializationObject[targetPropertyName] = sourceProperty.id;
  7103. break;
  7104. case 7:// Color Curves
  7105. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7106. break;
  7107. case 8:// Color 4
  7108. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7109. break;
  7110. case 9:// Image Processing
  7111. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7112. break;
  7113. }
  7114. }
  7115. }
  7116. return serializationObject;
  7117. };
  7118. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7119. if (rootUrl === void 0) { rootUrl = null; }
  7120. var destination = creationFunction();
  7121. if (!rootUrl) {
  7122. rootUrl = "";
  7123. }
  7124. // Tags
  7125. if (BABYLON.Tags) {
  7126. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7127. }
  7128. var classStore = getMergedStore(destination);
  7129. // Properties
  7130. for (var property in classStore) {
  7131. var propertyDescriptor = classStore[property];
  7132. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7133. var propertyType = propertyDescriptor.type;
  7134. if (sourceProperty !== undefined && sourceProperty !== null) {
  7135. var dest = destination;
  7136. switch (propertyType) {
  7137. case 0:// Value
  7138. dest[property] = sourceProperty;
  7139. break;
  7140. case 1:// Texture
  7141. if (scene) {
  7142. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7143. }
  7144. break;
  7145. case 2:// Color3
  7146. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7147. break;
  7148. case 3:// FresnelParameters
  7149. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7150. break;
  7151. case 4:// Vector2
  7152. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7153. break;
  7154. case 5:// Vector3
  7155. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7156. break;
  7157. case 6:// Mesh reference
  7158. if (scene) {
  7159. dest[property] = scene.getLastMeshByID(sourceProperty);
  7160. }
  7161. break;
  7162. case 7:// Color Curves
  7163. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7164. break;
  7165. case 8:// Color 4
  7166. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7167. break;
  7168. case 9:// Image Processing
  7169. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7170. break;
  7171. }
  7172. }
  7173. }
  7174. return destination;
  7175. };
  7176. SerializationHelper.Clone = function (creationFunction, source) {
  7177. return _copySource(creationFunction, source, false);
  7178. };
  7179. SerializationHelper.Instanciate = function (creationFunction, source) {
  7180. return _copySource(creationFunction, source, true);
  7181. };
  7182. return SerializationHelper;
  7183. }());
  7184. BABYLON.SerializationHelper = SerializationHelper;
  7185. })(BABYLON || (BABYLON = {}));
  7186. //# sourceMappingURL=babylon.decorators.js.map
  7187. var BABYLON;
  7188. (function (BABYLON) {
  7189. /**
  7190. * Wrapper class for promise with external resolve and reject.
  7191. */
  7192. var Deferred = /** @class */ (function () {
  7193. /**
  7194. * Constructor for this deferred object.
  7195. */
  7196. function Deferred() {
  7197. var _this = this;
  7198. this.promise = new Promise(function (resolve, reject) {
  7199. _this._resolve = resolve;
  7200. _this._reject = reject;
  7201. });
  7202. }
  7203. Object.defineProperty(Deferred.prototype, "resolve", {
  7204. /**
  7205. * The resolve method of the promise associated with this deferred object.
  7206. */
  7207. get: function () {
  7208. return this._resolve;
  7209. },
  7210. enumerable: true,
  7211. configurable: true
  7212. });
  7213. Object.defineProperty(Deferred.prototype, "reject", {
  7214. /**
  7215. * The reject method of the promise associated with this deferred object.
  7216. */
  7217. get: function () {
  7218. return this._reject;
  7219. },
  7220. enumerable: true,
  7221. configurable: true
  7222. });
  7223. return Deferred;
  7224. }());
  7225. BABYLON.Deferred = Deferred;
  7226. })(BABYLON || (BABYLON = {}));
  7227. //# sourceMappingURL=babylon.deferred.js.map
  7228. var BABYLON;
  7229. (function (BABYLON) {
  7230. /**
  7231. * A class serves as a medium between the observable and its observers
  7232. */
  7233. var EventState = /** @class */ (function () {
  7234. /**
  7235. * Create a new EventState
  7236. * @param mask defines the mask associated with this state
  7237. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7238. * @param target defines the original target of the state
  7239. * @param currentTarget defines the current target of the state
  7240. */
  7241. function EventState(mask, skipNextObservers, target, currentTarget) {
  7242. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7243. this.initalize(mask, skipNextObservers, target, currentTarget);
  7244. }
  7245. /**
  7246. * Initialize the current event state
  7247. * @param mask defines the mask associated with this state
  7248. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7249. * @param target defines the original target of the state
  7250. * @param currentTarget defines the current target of the state
  7251. * @returns the current event state
  7252. */
  7253. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7254. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7255. this.mask = mask;
  7256. this.skipNextObservers = skipNextObservers;
  7257. this.target = target;
  7258. this.currentTarget = currentTarget;
  7259. return this;
  7260. };
  7261. return EventState;
  7262. }());
  7263. BABYLON.EventState = EventState;
  7264. /**
  7265. * Represent an Observer registered to a given Observable object.
  7266. */
  7267. var Observer = /** @class */ (function () {
  7268. /**
  7269. * Creates a new observer
  7270. * @param callback defines the callback to call when the observer is notified
  7271. * @param mask defines the mask of the observer (used to filter notifications)
  7272. * @param scope defines the current scope used to restore the JS context
  7273. */
  7274. function Observer(
  7275. /**
  7276. * Defines the callback to call when the observer is notified
  7277. */
  7278. callback,
  7279. /**
  7280. * Defines the mask of the observer (used to filter notifications)
  7281. */
  7282. mask,
  7283. /**
  7284. * Defines the current scope used to restore the JS context
  7285. */
  7286. scope) {
  7287. if (scope === void 0) { scope = null; }
  7288. this.callback = callback;
  7289. this.mask = mask;
  7290. this.scope = scope;
  7291. /** @ignore */
  7292. this._willBeUnregistered = false;
  7293. /**
  7294. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7295. */
  7296. this.unregisterOnNextCall = false;
  7297. }
  7298. return Observer;
  7299. }());
  7300. BABYLON.Observer = Observer;
  7301. /**
  7302. * Represent a list of observers registered to multiple Observables object.
  7303. */
  7304. var MultiObserver = /** @class */ (function () {
  7305. function MultiObserver() {
  7306. }
  7307. /**
  7308. * Release associated resources
  7309. */
  7310. MultiObserver.prototype.dispose = function () {
  7311. if (this._observers && this._observables) {
  7312. for (var index = 0; index < this._observers.length; index++) {
  7313. this._observables[index].remove(this._observers[index]);
  7314. }
  7315. }
  7316. this._observers = null;
  7317. this._observables = null;
  7318. };
  7319. /**
  7320. * Raise a callback when one of the observable will notify
  7321. * @param observables defines a list of observables to watch
  7322. * @param callback defines the callback to call on notification
  7323. * @param mask defines the mask used to filter notifications
  7324. * @param scope defines the current scope used to restore the JS context
  7325. * @returns the new MultiObserver
  7326. */
  7327. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7328. if (mask === void 0) { mask = -1; }
  7329. if (scope === void 0) { scope = null; }
  7330. var result = new MultiObserver();
  7331. result._observers = new Array();
  7332. result._observables = observables;
  7333. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7334. var observable = observables_1[_i];
  7335. var observer = observable.add(callback, mask, false, scope);
  7336. if (observer) {
  7337. result._observers.push(observer);
  7338. }
  7339. }
  7340. return result;
  7341. };
  7342. return MultiObserver;
  7343. }());
  7344. BABYLON.MultiObserver = MultiObserver;
  7345. /**
  7346. * The Observable class is a simple implementation of the Observable pattern.
  7347. * 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.
  7348. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7349. * 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).
  7350. * 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.
  7351. */
  7352. var Observable = /** @class */ (function () {
  7353. /**
  7354. * Creates a new observable
  7355. * @param onObserverAdded defines a callback to call when a new observer is added
  7356. */
  7357. function Observable(onObserverAdded) {
  7358. this._observers = new Array();
  7359. this._eventState = new EventState(0);
  7360. if (onObserverAdded) {
  7361. this._onObserverAdded = onObserverAdded;
  7362. }
  7363. }
  7364. /**
  7365. * Create a new Observer with the specified callback
  7366. * @param callback the callback that will be executed for that Observer
  7367. * @param mask the mask used to filter observers
  7368. * @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.
  7369. * @param scope optional scope for the callback to be called from
  7370. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7371. * @returns the new observer created for the callback
  7372. */
  7373. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7374. if (mask === void 0) { mask = -1; }
  7375. if (insertFirst === void 0) { insertFirst = false; }
  7376. if (scope === void 0) { scope = null; }
  7377. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7378. if (!callback) {
  7379. return null;
  7380. }
  7381. var observer = new Observer(callback, mask, scope);
  7382. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7383. if (insertFirst) {
  7384. this._observers.unshift(observer);
  7385. }
  7386. else {
  7387. this._observers.push(observer);
  7388. }
  7389. if (this._onObserverAdded) {
  7390. this._onObserverAdded(observer);
  7391. }
  7392. return observer;
  7393. };
  7394. /**
  7395. * Remove an Observer from the Observable object
  7396. * @param observer the instance of the Observer to remove
  7397. * @returns false if it doesn't belong to this Observable
  7398. */
  7399. Observable.prototype.remove = function (observer) {
  7400. if (!observer) {
  7401. return false;
  7402. }
  7403. var index = this._observers.indexOf(observer);
  7404. if (index !== -1) {
  7405. this._observers.splice(index, 1);
  7406. return true;
  7407. }
  7408. return false;
  7409. };
  7410. /**
  7411. * Remove a callback from the Observable object
  7412. * @param callback the callback to remove
  7413. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7414. * @returns false if it doesn't belong to this Observable
  7415. */
  7416. Observable.prototype.removeCallback = function (callback, scope) {
  7417. for (var index = 0; index < this._observers.length; index++) {
  7418. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7419. this._observers.splice(index, 1);
  7420. return true;
  7421. }
  7422. }
  7423. return false;
  7424. };
  7425. Observable.prototype._deferUnregister = function (observer) {
  7426. var _this = this;
  7427. observer.unregisterOnNextCall = false;
  7428. observer._willBeUnregistered = true;
  7429. BABYLON.Tools.SetImmediate(function () {
  7430. _this.remove(observer);
  7431. });
  7432. };
  7433. /**
  7434. * Notify all Observers by calling their respective callback with the given data
  7435. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7436. * @param eventData defines the data to send to all observers
  7437. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7438. * @param target defines the original target of the state
  7439. * @param currentTarget defines the current target of the state
  7440. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7441. */
  7442. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7443. if (mask === void 0) { mask = -1; }
  7444. if (!this._observers.length) {
  7445. return true;
  7446. }
  7447. var state = this._eventState;
  7448. state.mask = mask;
  7449. state.target = target;
  7450. state.currentTarget = currentTarget;
  7451. state.skipNextObservers = false;
  7452. state.lastReturnValue = eventData;
  7453. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7454. var obs = _a[_i];
  7455. if (obs._willBeUnregistered) {
  7456. continue;
  7457. }
  7458. if (obs.mask & mask) {
  7459. if (obs.scope) {
  7460. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7461. }
  7462. else {
  7463. state.lastReturnValue = obs.callback(eventData, state);
  7464. }
  7465. if (obs.unregisterOnNextCall) {
  7466. this._deferUnregister(obs);
  7467. }
  7468. }
  7469. if (state.skipNextObservers) {
  7470. return false;
  7471. }
  7472. }
  7473. return true;
  7474. };
  7475. /**
  7476. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7477. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7478. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7479. * and it is crucial that all callbacks will be executed.
  7480. * The order of the callbacks is kept, callbacks are not executed parallel.
  7481. *
  7482. * @param eventData The data to be sent to each callback
  7483. * @param mask is used to filter observers defaults to -1
  7484. * @param target defines the callback target (see EventState)
  7485. * @param currentTarget defines he current object in the bubbling phase
  7486. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7487. */
  7488. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7489. var _this = this;
  7490. if (mask === void 0) { mask = -1; }
  7491. // create an empty promise
  7492. var p = Promise.resolve(eventData);
  7493. // no observers? return this promise.
  7494. if (!this._observers.length) {
  7495. return p;
  7496. }
  7497. var state = this._eventState;
  7498. state.mask = mask;
  7499. state.target = target;
  7500. state.currentTarget = currentTarget;
  7501. state.skipNextObservers = false;
  7502. // execute one callback after another (not using Promise.all, the order is important)
  7503. this._observers.forEach(function (obs) {
  7504. if (state.skipNextObservers) {
  7505. return;
  7506. }
  7507. if (obs._willBeUnregistered) {
  7508. return;
  7509. }
  7510. if (obs.mask & mask) {
  7511. if (obs.scope) {
  7512. p = p.then(function (lastReturnedValue) {
  7513. state.lastReturnValue = lastReturnedValue;
  7514. return obs.callback.apply(obs.scope, [eventData, state]);
  7515. });
  7516. }
  7517. else {
  7518. p = p.then(function (lastReturnedValue) {
  7519. state.lastReturnValue = lastReturnedValue;
  7520. return obs.callback(eventData, state);
  7521. });
  7522. }
  7523. if (obs.unregisterOnNextCall) {
  7524. _this._deferUnregister(obs);
  7525. }
  7526. }
  7527. });
  7528. // return the eventData
  7529. return p.then(function () { return eventData; });
  7530. };
  7531. /**
  7532. * Notify a specific observer
  7533. * @param observer defines the observer to notify
  7534. * @param eventData defines the data to be sent to each callback
  7535. * @param mask is used to filter observers defaults to -1
  7536. */
  7537. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7538. if (mask === void 0) { mask = -1; }
  7539. var state = this._eventState;
  7540. state.mask = mask;
  7541. state.skipNextObservers = false;
  7542. observer.callback(eventData, state);
  7543. };
  7544. /**
  7545. * Gets a boolean indicating if the observable has at least one observer
  7546. * @returns true is the Observable has at least one Observer registered
  7547. */
  7548. Observable.prototype.hasObservers = function () {
  7549. return this._observers.length > 0;
  7550. };
  7551. /**
  7552. * Clear the list of observers
  7553. */
  7554. Observable.prototype.clear = function () {
  7555. this._observers = new Array();
  7556. this._onObserverAdded = null;
  7557. };
  7558. /**
  7559. * Clone the current observable
  7560. * @returns a new observable
  7561. */
  7562. Observable.prototype.clone = function () {
  7563. var result = new Observable();
  7564. result._observers = this._observers.slice(0);
  7565. return result;
  7566. };
  7567. /**
  7568. * Does this observable handles observer registered with a given mask
  7569. * @param mask defines the mask to be tested
  7570. * @return whether or not one observer registered with the given mask is handeled
  7571. **/
  7572. Observable.prototype.hasSpecificMask = function (mask) {
  7573. if (mask === void 0) { mask = -1; }
  7574. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7575. var obs = _a[_i];
  7576. if (obs.mask & mask || obs.mask === mask) {
  7577. return true;
  7578. }
  7579. }
  7580. return false;
  7581. };
  7582. return Observable;
  7583. }());
  7584. BABYLON.Observable = Observable;
  7585. })(BABYLON || (BABYLON = {}));
  7586. //# sourceMappingURL=babylon.observable.js.map
  7587. var BABYLON;
  7588. (function (BABYLON) {
  7589. var SmartArray = /** @class */ (function () {
  7590. function SmartArray(capacity) {
  7591. this.length = 0;
  7592. this.data = new Array(capacity);
  7593. this._id = SmartArray._GlobalId++;
  7594. }
  7595. SmartArray.prototype.push = function (value) {
  7596. this.data[this.length++] = value;
  7597. if (this.length > this.data.length) {
  7598. this.data.length *= 2;
  7599. }
  7600. };
  7601. SmartArray.prototype.forEach = function (func) {
  7602. for (var index = 0; index < this.length; index++) {
  7603. func(this.data[index]);
  7604. }
  7605. };
  7606. SmartArray.prototype.sort = function (compareFn) {
  7607. this.data.sort(compareFn);
  7608. };
  7609. SmartArray.prototype.reset = function () {
  7610. this.length = 0;
  7611. };
  7612. SmartArray.prototype.dispose = function () {
  7613. this.reset();
  7614. if (this.data) {
  7615. this.data.length = 0;
  7616. this.data = [];
  7617. }
  7618. };
  7619. SmartArray.prototype.concat = function (array) {
  7620. if (array.length === 0) {
  7621. return;
  7622. }
  7623. if (this.length + array.length > this.data.length) {
  7624. this.data.length = (this.length + array.length) * 2;
  7625. }
  7626. for (var index = 0; index < array.length; index++) {
  7627. this.data[this.length++] = (array.data || array)[index];
  7628. }
  7629. };
  7630. SmartArray.prototype.indexOf = function (value) {
  7631. var position = this.data.indexOf(value);
  7632. if (position >= this.length) {
  7633. return -1;
  7634. }
  7635. return position;
  7636. };
  7637. SmartArray.prototype.contains = function (value) {
  7638. return this.data.indexOf(value) !== -1;
  7639. };
  7640. // Statics
  7641. SmartArray._GlobalId = 0;
  7642. return SmartArray;
  7643. }());
  7644. BABYLON.SmartArray = SmartArray;
  7645. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7646. __extends(SmartArrayNoDuplicate, _super);
  7647. function SmartArrayNoDuplicate() {
  7648. var _this = _super !== null && _super.apply(this, arguments) || this;
  7649. _this._duplicateId = 0;
  7650. return _this;
  7651. }
  7652. SmartArrayNoDuplicate.prototype.push = function (value) {
  7653. _super.prototype.push.call(this, value);
  7654. if (!value.__smartArrayFlags) {
  7655. value.__smartArrayFlags = {};
  7656. }
  7657. value.__smartArrayFlags[this._id] = this._duplicateId;
  7658. };
  7659. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7660. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7661. return false;
  7662. }
  7663. this.push(value);
  7664. return true;
  7665. };
  7666. SmartArrayNoDuplicate.prototype.reset = function () {
  7667. _super.prototype.reset.call(this);
  7668. this._duplicateId++;
  7669. };
  7670. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7671. if (array.length === 0) {
  7672. return;
  7673. }
  7674. if (this.length + array.length > this.data.length) {
  7675. this.data.length = (this.length + array.length) * 2;
  7676. }
  7677. for (var index = 0; index < array.length; index++) {
  7678. var item = (array.data || array)[index];
  7679. this.pushNoDuplicate(item);
  7680. }
  7681. };
  7682. return SmartArrayNoDuplicate;
  7683. }(SmartArray));
  7684. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7685. })(BABYLON || (BABYLON = {}));
  7686. //# sourceMappingURL=babylon.smartArray.js.map
  7687. var BABYLON;
  7688. (function (BABYLON) {
  7689. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7690. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7691. var LoadFileError = /** @class */ (function (_super) {
  7692. __extends(LoadFileError, _super);
  7693. function LoadFileError(message, request) {
  7694. var _this = _super.call(this, message) || this;
  7695. _this.request = request;
  7696. _this.name = "LoadFileError";
  7697. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7698. return _this;
  7699. }
  7700. // Polyfill for Object.setPrototypeOf if necessary.
  7701. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7702. return LoadFileError;
  7703. }(Error));
  7704. BABYLON.LoadFileError = LoadFileError;
  7705. var RetryStrategy = /** @class */ (function () {
  7706. function RetryStrategy() {
  7707. }
  7708. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7709. if (maxRetries === void 0) { maxRetries = 3; }
  7710. if (baseInterval === void 0) { baseInterval = 500; }
  7711. return function (url, request, retryIndex) {
  7712. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7713. return -1;
  7714. }
  7715. return Math.pow(2, retryIndex) * baseInterval;
  7716. };
  7717. };
  7718. return RetryStrategy;
  7719. }());
  7720. BABYLON.RetryStrategy = RetryStrategy;
  7721. // Screenshots
  7722. var screenshotCanvas;
  7723. var cloneValue = function (source, destinationObject) {
  7724. if (!source)
  7725. return null;
  7726. if (source instanceof BABYLON.Mesh) {
  7727. return null;
  7728. }
  7729. if (source instanceof BABYLON.SubMesh) {
  7730. return source.clone(destinationObject);
  7731. }
  7732. else if (source.clone) {
  7733. return source.clone();
  7734. }
  7735. return null;
  7736. };
  7737. var Tools = /** @class */ (function () {
  7738. function Tools() {
  7739. }
  7740. /**
  7741. * Interpolates between a and b via alpha
  7742. * @param a The lower value (returned when alpha = 0)
  7743. * @param b The upper value (returned when alpha = 1)
  7744. * @param alpha The interpolation-factor
  7745. * @return The mixed value
  7746. */
  7747. Tools.Mix = function (a, b, alpha) {
  7748. return a * (1 - alpha) + b * alpha;
  7749. };
  7750. Tools.Instantiate = function (className) {
  7751. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7752. return Tools.RegisteredExternalClasses[className];
  7753. }
  7754. var arr = className.split(".");
  7755. var fn = (window || this);
  7756. for (var i = 0, len = arr.length; i < len; i++) {
  7757. fn = fn[arr[i]];
  7758. }
  7759. if (typeof fn !== "function") {
  7760. return null;
  7761. }
  7762. return fn;
  7763. };
  7764. /**
  7765. * Provides a slice function that will work even on IE
  7766. * @param data defines the array to slice
  7767. * @returns the new sliced array
  7768. */
  7769. Tools.Slice = function (data) {
  7770. if (data.slice) {
  7771. return data.slice();
  7772. }
  7773. return Array.prototype.slice.call(data);
  7774. };
  7775. Tools.SetImmediate = function (action) {
  7776. if (window.setImmediate) {
  7777. window.setImmediate(action);
  7778. }
  7779. else {
  7780. setTimeout(action, 1);
  7781. }
  7782. };
  7783. Tools.IsExponentOfTwo = function (value) {
  7784. var count = 1;
  7785. do {
  7786. count *= 2;
  7787. } while (count < value);
  7788. return count === value;
  7789. };
  7790. /**
  7791. * Find the next highest power of two.
  7792. * @param x Number to start search from.
  7793. * @return Next highest power of two.
  7794. */
  7795. Tools.CeilingPOT = function (x) {
  7796. x--;
  7797. x |= x >> 1;
  7798. x |= x >> 2;
  7799. x |= x >> 4;
  7800. x |= x >> 8;
  7801. x |= x >> 16;
  7802. x++;
  7803. return x;
  7804. };
  7805. /**
  7806. * Find the next lowest power of two.
  7807. * @param x Number to start search from.
  7808. * @return Next lowest power of two.
  7809. */
  7810. Tools.FloorPOT = function (x) {
  7811. x = x | (x >> 1);
  7812. x = x | (x >> 2);
  7813. x = x | (x >> 4);
  7814. x = x | (x >> 8);
  7815. x = x | (x >> 16);
  7816. return x - (x >> 1);
  7817. };
  7818. /**
  7819. * Find the nearest power of two.
  7820. * @param x Number to start search from.
  7821. * @return Next nearest power of two.
  7822. */
  7823. Tools.NearestPOT = function (x) {
  7824. var c = Tools.CeilingPOT(x);
  7825. var f = Tools.FloorPOT(x);
  7826. return (c - x) > (x - f) ? f : c;
  7827. };
  7828. Tools.GetExponentOfTwo = function (value, max, mode) {
  7829. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7830. var pot;
  7831. switch (mode) {
  7832. case BABYLON.Engine.SCALEMODE_FLOOR:
  7833. pot = Tools.FloorPOT(value);
  7834. break;
  7835. case BABYLON.Engine.SCALEMODE_NEAREST:
  7836. pot = Tools.NearestPOT(value);
  7837. break;
  7838. case BABYLON.Engine.SCALEMODE_CEILING:
  7839. default:
  7840. pot = Tools.CeilingPOT(value);
  7841. break;
  7842. }
  7843. return Math.min(pot, max);
  7844. };
  7845. Tools.GetFilename = function (path) {
  7846. var index = path.lastIndexOf("/");
  7847. if (index < 0)
  7848. return path;
  7849. return path.substring(index + 1);
  7850. };
  7851. /**
  7852. * Extracts the "folder" part of a path (everything before the filename).
  7853. * @param uri The URI to extract the info from
  7854. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7855. * @returns The "folder" part of the path
  7856. */
  7857. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7858. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7859. var index = uri.lastIndexOf("/");
  7860. if (index < 0) {
  7861. if (returnUnchangedIfNoSlash) {
  7862. return uri;
  7863. }
  7864. return "";
  7865. }
  7866. return uri.substring(0, index + 1);
  7867. };
  7868. Tools.GetDOMTextContent = function (element) {
  7869. var result = "";
  7870. var child = element.firstChild;
  7871. while (child) {
  7872. if (child.nodeType === 3) {
  7873. result += child.textContent;
  7874. }
  7875. child = child.nextSibling;
  7876. }
  7877. return result;
  7878. };
  7879. Tools.ToDegrees = function (angle) {
  7880. return angle * 180 / Math.PI;
  7881. };
  7882. Tools.ToRadians = function (angle) {
  7883. return angle * Math.PI / 180;
  7884. };
  7885. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7886. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7887. var output = "";
  7888. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7889. var i = 0;
  7890. var bytes = new Uint8Array(buffer);
  7891. while (i < bytes.length) {
  7892. chr1 = bytes[i++];
  7893. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7894. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7895. enc1 = chr1 >> 2;
  7896. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7897. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7898. enc4 = chr3 & 63;
  7899. if (isNaN(chr2)) {
  7900. enc3 = enc4 = 64;
  7901. }
  7902. else if (isNaN(chr3)) {
  7903. enc4 = 64;
  7904. }
  7905. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7906. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7907. }
  7908. return "data:image/png;base64," + output;
  7909. };
  7910. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7911. if (bias === void 0) { bias = null; }
  7912. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7913. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7914. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7915. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7916. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7917. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7918. }
  7919. if (bias) {
  7920. minimum.x -= minimum.x * bias.x + bias.y;
  7921. minimum.y -= minimum.y * bias.x + bias.y;
  7922. minimum.z -= minimum.z * bias.x + bias.y;
  7923. maximum.x += maximum.x * bias.x + bias.y;
  7924. maximum.y += maximum.y * bias.x + bias.y;
  7925. maximum.z += maximum.z * bias.x + bias.y;
  7926. }
  7927. return {
  7928. minimum: minimum,
  7929. maximum: maximum
  7930. };
  7931. };
  7932. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7933. if (bias === void 0) { bias = null; }
  7934. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7935. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7936. if (!stride) {
  7937. stride = 3;
  7938. }
  7939. for (var index = start; index < start + count; index++) {
  7940. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7941. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7942. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7943. }
  7944. if (bias) {
  7945. minimum.x -= minimum.x * bias.x + bias.y;
  7946. minimum.y -= minimum.y * bias.x + bias.y;
  7947. minimum.z -= minimum.z * bias.x + bias.y;
  7948. maximum.x += maximum.x * bias.x + bias.y;
  7949. maximum.y += maximum.y * bias.x + bias.y;
  7950. maximum.z += maximum.z * bias.x + bias.y;
  7951. }
  7952. return {
  7953. minimum: minimum,
  7954. maximum: maximum
  7955. };
  7956. };
  7957. Tools.Vector2ArrayFeeder = function (array) {
  7958. return function (index) {
  7959. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7960. var length = isFloatArray ? array.length / 2 : array.length;
  7961. if (index >= length) {
  7962. return null;
  7963. }
  7964. if (isFloatArray) {
  7965. var fa = array;
  7966. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7967. }
  7968. var a = array;
  7969. return a[index];
  7970. };
  7971. };
  7972. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7973. if (bias === void 0) { bias = null; }
  7974. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7975. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7976. var i = 0;
  7977. var cur = feeder(i++);
  7978. while (cur) {
  7979. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7980. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7981. cur = feeder(i++);
  7982. }
  7983. if (bias) {
  7984. minimum.x -= minimum.x * bias.x + bias.y;
  7985. minimum.y -= minimum.y * bias.x + bias.y;
  7986. maximum.x += maximum.x * bias.x + bias.y;
  7987. maximum.y += maximum.y * bias.x + bias.y;
  7988. }
  7989. return {
  7990. minimum: minimum,
  7991. maximum: maximum
  7992. };
  7993. };
  7994. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7995. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7996. return null;
  7997. return Array.isArray(obj) ? obj : [obj];
  7998. };
  7999. // Misc.
  8000. Tools.GetPointerPrefix = function () {
  8001. var eventPrefix = "pointer";
  8002. // Check if pointer events are supported
  8003. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8004. eventPrefix = "mouse";
  8005. }
  8006. return eventPrefix;
  8007. };
  8008. /**
  8009. * @param func - the function to be called
  8010. * @param requester - the object that will request the next frame. Falls back to window.
  8011. */
  8012. Tools.QueueNewFrame = function (func, requester) {
  8013. if (!Tools.IsWindowObjectExist()) {
  8014. return setTimeout(func, 16);
  8015. }
  8016. if (!requester) {
  8017. requester = window;
  8018. }
  8019. if (requester.requestAnimationFrame) {
  8020. return requester.requestAnimationFrame(func);
  8021. }
  8022. else if (requester.msRequestAnimationFrame) {
  8023. return requester.msRequestAnimationFrame(func);
  8024. }
  8025. else if (requester.webkitRequestAnimationFrame) {
  8026. return requester.webkitRequestAnimationFrame(func);
  8027. }
  8028. else if (requester.mozRequestAnimationFrame) {
  8029. return requester.mozRequestAnimationFrame(func);
  8030. }
  8031. else if (requester.oRequestAnimationFrame) {
  8032. return requester.oRequestAnimationFrame(func);
  8033. }
  8034. else {
  8035. return window.setTimeout(func, 16);
  8036. }
  8037. };
  8038. Tools.RequestFullscreen = function (element) {
  8039. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8040. if (!requestFunction)
  8041. return;
  8042. requestFunction.call(element);
  8043. };
  8044. Tools.ExitFullscreen = function () {
  8045. if (document.exitFullscreen) {
  8046. document.exitFullscreen();
  8047. }
  8048. else if (document.mozCancelFullScreen) {
  8049. document.mozCancelFullScreen();
  8050. }
  8051. else if (document.webkitCancelFullScreen) {
  8052. document.webkitCancelFullScreen();
  8053. }
  8054. else if (document.msCancelFullScreen) {
  8055. document.msCancelFullScreen();
  8056. }
  8057. };
  8058. Tools.SetCorsBehavior = function (url, element) {
  8059. if (url && url.indexOf("data:") === 0) {
  8060. return;
  8061. }
  8062. if (Tools.CorsBehavior) {
  8063. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8064. element.crossOrigin = Tools.CorsBehavior;
  8065. }
  8066. else {
  8067. var result = Tools.CorsBehavior(url);
  8068. if (result) {
  8069. element.crossOrigin = result;
  8070. }
  8071. }
  8072. }
  8073. };
  8074. // External files
  8075. Tools.CleanUrl = function (url) {
  8076. url = url.replace(/#/mg, "%23");
  8077. return url;
  8078. };
  8079. Tools.LoadImage = function (url, onLoad, onError, database) {
  8080. if (url instanceof ArrayBuffer) {
  8081. url = Tools.EncodeArrayBufferTobase64(url);
  8082. }
  8083. url = Tools.CleanUrl(url);
  8084. url = Tools.PreprocessUrl(url);
  8085. var img = new Image();
  8086. Tools.SetCorsBehavior(url, img);
  8087. var loadHandler = function () {
  8088. img.removeEventListener("load", loadHandler);
  8089. img.removeEventListener("error", errorHandler);
  8090. onLoad(img);
  8091. };
  8092. var errorHandler = function (err) {
  8093. img.removeEventListener("load", loadHandler);
  8094. img.removeEventListener("error", errorHandler);
  8095. Tools.Error("Error while trying to load image: " + url);
  8096. if (onError) {
  8097. onError("Error while trying to load image: " + url, err);
  8098. }
  8099. };
  8100. img.addEventListener("load", loadHandler);
  8101. img.addEventListener("error", errorHandler);
  8102. var noIndexedDB = function () {
  8103. img.src = url;
  8104. };
  8105. var loadFromIndexedDB = function () {
  8106. if (database) {
  8107. database.loadImageFromDB(url, img);
  8108. }
  8109. };
  8110. //ANY database to do!
  8111. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8112. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8113. }
  8114. else {
  8115. if (url.indexOf("file:") !== -1) {
  8116. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8117. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8118. try {
  8119. var blobURL;
  8120. try {
  8121. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8122. }
  8123. catch (ex) {
  8124. // Chrome doesn't support oneTimeOnly parameter
  8125. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8126. }
  8127. img.src = blobURL;
  8128. }
  8129. catch (e) {
  8130. img.src = "";
  8131. }
  8132. return img;
  8133. }
  8134. }
  8135. noIndexedDB();
  8136. }
  8137. return img;
  8138. };
  8139. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8140. url = Tools.CleanUrl(url);
  8141. url = Tools.PreprocessUrl(url);
  8142. // If file and file input are set
  8143. if (url.indexOf("file:") !== -1) {
  8144. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8145. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8146. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8147. }
  8148. }
  8149. var loadUrl = Tools.BaseUrl + url;
  8150. var aborted = false;
  8151. var fileRequest = {
  8152. onCompleteObservable: new BABYLON.Observable(),
  8153. abort: function () { return aborted = true; },
  8154. };
  8155. var requestFile = function () {
  8156. var request = new XMLHttpRequest();
  8157. var retryHandle = null;
  8158. fileRequest.abort = function () {
  8159. aborted = true;
  8160. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8161. request.abort();
  8162. }
  8163. if (retryHandle !== null) {
  8164. clearTimeout(retryHandle);
  8165. retryHandle = null;
  8166. }
  8167. };
  8168. var retryLoop = function (retryIndex) {
  8169. request.open('GET', loadUrl, true);
  8170. if (useArrayBuffer) {
  8171. request.responseType = "arraybuffer";
  8172. }
  8173. if (onProgress) {
  8174. request.addEventListener("progress", onProgress);
  8175. }
  8176. var onLoadEnd = function () {
  8177. request.removeEventListener("loadend", onLoadEnd);
  8178. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8179. fileRequest.onCompleteObservable.clear();
  8180. };
  8181. request.addEventListener("loadend", onLoadEnd);
  8182. var onReadyStateChange = function () {
  8183. if (aborted) {
  8184. return;
  8185. }
  8186. // In case of undefined state in some browsers.
  8187. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8188. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8189. request.removeEventListener("readystatechange", onReadyStateChange);
  8190. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8191. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8192. return;
  8193. }
  8194. var retryStrategy = Tools.DefaultRetryStrategy;
  8195. if (retryStrategy) {
  8196. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8197. if (waitTime !== -1) {
  8198. // Prevent the request from completing for retry.
  8199. request.removeEventListener("loadend", onLoadEnd);
  8200. request = new XMLHttpRequest();
  8201. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8202. return;
  8203. }
  8204. }
  8205. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8206. if (onError) {
  8207. onError(request, e);
  8208. }
  8209. else {
  8210. throw e;
  8211. }
  8212. }
  8213. };
  8214. request.addEventListener("readystatechange", onReadyStateChange);
  8215. request.send();
  8216. };
  8217. retryLoop(0);
  8218. };
  8219. // Caching all files
  8220. if (database && database.enableSceneOffline) {
  8221. var noIndexedDB_1 = function () {
  8222. if (!aborted) {
  8223. requestFile();
  8224. }
  8225. };
  8226. var loadFromIndexedDB = function () {
  8227. // TODO: database needs to support aborting and should return a IFileRequest
  8228. if (aborted) {
  8229. return;
  8230. }
  8231. if (database) {
  8232. database.loadFileFromDB(url, function (data) {
  8233. if (!aborted) {
  8234. onSuccess(data);
  8235. }
  8236. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8237. }, onProgress ? function (event) {
  8238. if (!aborted) {
  8239. onProgress(event);
  8240. }
  8241. } : undefined, noIndexedDB_1, useArrayBuffer);
  8242. }
  8243. };
  8244. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8245. }
  8246. else {
  8247. requestFile();
  8248. }
  8249. return fileRequest;
  8250. };
  8251. /**
  8252. * Load a script (identified by an url). When the url returns, the
  8253. * content of this file is added into a new script element, attached to the DOM (body element)
  8254. */
  8255. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8256. var head = document.getElementsByTagName('head')[0];
  8257. var script = document.createElement('script');
  8258. script.type = 'text/javascript';
  8259. script.src = scriptUrl;
  8260. script.onload = function () {
  8261. if (onSuccess) {
  8262. onSuccess();
  8263. }
  8264. };
  8265. script.onerror = function (e) {
  8266. if (onError) {
  8267. onError("Unable to load script", e);
  8268. }
  8269. };
  8270. head.appendChild(script);
  8271. };
  8272. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8273. var reader = new FileReader();
  8274. var request = {
  8275. onCompleteObservable: new BABYLON.Observable(),
  8276. abort: function () { return reader.abort(); },
  8277. };
  8278. reader.onloadend = function (e) {
  8279. request.onCompleteObservable.notifyObservers(request);
  8280. };
  8281. reader.onload = function (e) {
  8282. //target doesn't have result from ts 1.3
  8283. callback(e.target['result']);
  8284. };
  8285. reader.onprogress = progressCallback;
  8286. reader.readAsDataURL(fileToLoad);
  8287. return request;
  8288. };
  8289. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8290. var reader = new FileReader();
  8291. var request = {
  8292. onCompleteObservable: new BABYLON.Observable(),
  8293. abort: function () { return reader.abort(); },
  8294. };
  8295. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8296. reader.onerror = function (e) {
  8297. Tools.Log("Error while reading file: " + fileToLoad.name);
  8298. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8299. };
  8300. reader.onload = function (e) {
  8301. //target doesn't have result from ts 1.3
  8302. callback(e.target['result']);
  8303. };
  8304. if (progressCallBack) {
  8305. reader.onprogress = progressCallBack;
  8306. }
  8307. if (!useArrayBuffer) {
  8308. // Asynchronous read
  8309. reader.readAsText(fileToLoad);
  8310. }
  8311. else {
  8312. reader.readAsArrayBuffer(fileToLoad);
  8313. }
  8314. return request;
  8315. };
  8316. //returns a downloadable url to a file content.
  8317. Tools.FileAsURL = function (content) {
  8318. var fileBlob = new Blob([content]);
  8319. var url = window.URL || window.webkitURL;
  8320. var link = url.createObjectURL(fileBlob);
  8321. return link;
  8322. };
  8323. // Misc.
  8324. Tools.Format = function (value, decimals) {
  8325. if (decimals === void 0) { decimals = 2; }
  8326. return value.toFixed(decimals);
  8327. };
  8328. Tools.CheckExtends = function (v, min, max) {
  8329. if (v.x < min.x)
  8330. min.x = v.x;
  8331. if (v.y < min.y)
  8332. min.y = v.y;
  8333. if (v.z < min.z)
  8334. min.z = v.z;
  8335. if (v.x > max.x)
  8336. max.x = v.x;
  8337. if (v.y > max.y)
  8338. max.y = v.y;
  8339. if (v.z > max.z)
  8340. max.z = v.z;
  8341. };
  8342. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8343. for (var prop in source) {
  8344. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8345. continue;
  8346. }
  8347. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8348. continue;
  8349. }
  8350. var sourceValue = source[prop];
  8351. var typeOfSourceValue = typeof sourceValue;
  8352. if (typeOfSourceValue === "function") {
  8353. continue;
  8354. }
  8355. if (typeOfSourceValue === "object") {
  8356. if (sourceValue instanceof Array) {
  8357. destination[prop] = [];
  8358. if (sourceValue.length > 0) {
  8359. if (typeof sourceValue[0] == "object") {
  8360. for (var index = 0; index < sourceValue.length; index++) {
  8361. var clonedValue = cloneValue(sourceValue[index], destination);
  8362. if (destination[prop].indexOf(clonedValue) === -1) {
  8363. destination[prop].push(clonedValue);
  8364. }
  8365. }
  8366. }
  8367. else {
  8368. destination[prop] = sourceValue.slice(0);
  8369. }
  8370. }
  8371. }
  8372. else {
  8373. destination[prop] = cloneValue(sourceValue, destination);
  8374. }
  8375. }
  8376. else {
  8377. destination[prop] = sourceValue;
  8378. }
  8379. }
  8380. };
  8381. Tools.IsEmpty = function (obj) {
  8382. for (var i in obj) {
  8383. if (obj.hasOwnProperty(i)) {
  8384. return false;
  8385. }
  8386. }
  8387. return true;
  8388. };
  8389. Tools.RegisterTopRootEvents = function (events) {
  8390. for (var index = 0; index < events.length; index++) {
  8391. var event = events[index];
  8392. window.addEventListener(event.name, event.handler, false);
  8393. try {
  8394. if (window.parent) {
  8395. window.parent.addEventListener(event.name, event.handler, false);
  8396. }
  8397. }
  8398. catch (e) {
  8399. // Silently fails...
  8400. }
  8401. }
  8402. };
  8403. Tools.UnregisterTopRootEvents = function (events) {
  8404. for (var index = 0; index < events.length; index++) {
  8405. var event = events[index];
  8406. window.removeEventListener(event.name, event.handler);
  8407. try {
  8408. if (window.parent) {
  8409. window.parent.removeEventListener(event.name, event.handler);
  8410. }
  8411. }
  8412. catch (e) {
  8413. // Silently fails...
  8414. }
  8415. }
  8416. };
  8417. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8418. if (mimeType === void 0) { mimeType = "image/png"; }
  8419. // Read the contents of the framebuffer
  8420. var numberOfChannelsByLine = width * 4;
  8421. var halfHeight = height / 2;
  8422. //Reading datas from WebGL
  8423. var data = engine.readPixels(0, 0, width, height);
  8424. //To flip image on Y axis.
  8425. for (var i = 0; i < halfHeight; i++) {
  8426. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8427. var currentCell = j + i * numberOfChannelsByLine;
  8428. var targetLine = height - i - 1;
  8429. var targetCell = j + targetLine * numberOfChannelsByLine;
  8430. var temp = data[currentCell];
  8431. data[currentCell] = data[targetCell];
  8432. data[targetCell] = temp;
  8433. }
  8434. }
  8435. // Create a 2D canvas to store the result
  8436. if (!screenshotCanvas) {
  8437. screenshotCanvas = document.createElement('canvas');
  8438. }
  8439. screenshotCanvas.width = width;
  8440. screenshotCanvas.height = height;
  8441. var context = screenshotCanvas.getContext('2d');
  8442. if (context) {
  8443. // Copy the pixels to a 2D canvas
  8444. var imageData = context.createImageData(width, height);
  8445. var castData = (imageData.data);
  8446. castData.set(data);
  8447. context.putImageData(imageData, 0, 0);
  8448. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8449. }
  8450. };
  8451. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8452. if (mimeType === void 0) { mimeType = "image/png"; }
  8453. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8454. if (successCallback) {
  8455. successCallback(base64Image);
  8456. }
  8457. else {
  8458. // We need HTMLCanvasElement.toBlob for HD screenshots
  8459. if (!screenshotCanvas.toBlob) {
  8460. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8461. screenshotCanvas.toBlob = function (callback, type, quality) {
  8462. var _this = this;
  8463. setTimeout(function () {
  8464. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8465. for (var i = 0; i < len; i++) {
  8466. arr[i] = binStr.charCodeAt(i);
  8467. }
  8468. callback(new Blob([arr], { type: type || 'image/png' }));
  8469. });
  8470. };
  8471. }
  8472. screenshotCanvas.toBlob(function (blob) {
  8473. var url = URL.createObjectURL(blob);
  8474. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8475. if (("download" in document.createElement("a"))) {
  8476. var a = window.document.createElement("a");
  8477. a.href = url;
  8478. if (fileName) {
  8479. a.setAttribute("download", fileName);
  8480. }
  8481. else {
  8482. var date = new Date();
  8483. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8484. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8485. }
  8486. window.document.body.appendChild(a);
  8487. a.addEventListener("click", function () {
  8488. if (a.parentElement) {
  8489. a.parentElement.removeChild(a);
  8490. }
  8491. });
  8492. a.click();
  8493. }
  8494. else {
  8495. var newWindow = window.open("");
  8496. if (!newWindow)
  8497. return;
  8498. var img = newWindow.document.createElement("img");
  8499. img.onload = function () {
  8500. // no longer need to read the blob so it's revoked
  8501. URL.revokeObjectURL(url);
  8502. };
  8503. img.src = url;
  8504. newWindow.document.body.appendChild(img);
  8505. }
  8506. });
  8507. }
  8508. };
  8509. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8510. if (mimeType === void 0) { mimeType = "image/png"; }
  8511. var width;
  8512. var height;
  8513. // If a precision value is specified
  8514. if (size.precision) {
  8515. width = Math.round(engine.getRenderWidth() * size.precision);
  8516. height = Math.round(width / engine.getAspectRatio(camera));
  8517. }
  8518. else if (size.width && size.height) {
  8519. width = size.width;
  8520. height = size.height;
  8521. }
  8522. else if (size.width && !size.height) {
  8523. width = size.width;
  8524. height = Math.round(width / engine.getAspectRatio(camera));
  8525. }
  8526. else if (size.height && !size.width) {
  8527. height = size.height;
  8528. width = Math.round(height * engine.getAspectRatio(camera));
  8529. }
  8530. else if (!isNaN(size)) {
  8531. height = size;
  8532. width = size;
  8533. }
  8534. else {
  8535. Tools.Error("Invalid 'size' parameter !");
  8536. return;
  8537. }
  8538. if (!screenshotCanvas) {
  8539. screenshotCanvas = document.createElement('canvas');
  8540. }
  8541. screenshotCanvas.width = width;
  8542. screenshotCanvas.height = height;
  8543. var renderContext = screenshotCanvas.getContext("2d");
  8544. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8545. var newWidth = width;
  8546. var newHeight = newWidth / ratio;
  8547. if (newHeight > height) {
  8548. newHeight = height;
  8549. newWidth = newHeight * ratio;
  8550. }
  8551. var offsetX = Math.max(0, width - newWidth) / 2;
  8552. var offsetY = Math.max(0, height - newHeight) / 2;
  8553. var renderingCanvas = engine.getRenderingCanvas();
  8554. if (renderContext && renderingCanvas) {
  8555. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8556. }
  8557. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8558. };
  8559. /**
  8560. * Generates an image screenshot from the specified camera.
  8561. *
  8562. * @param engine The engine to use for rendering
  8563. * @param camera The camera to use for rendering
  8564. * @param size This parameter can be set to a single number or to an object with the
  8565. * following (optional) properties: precision, width, height. If a single number is passed,
  8566. * it will be used for both width and height. If an object is passed, the screenshot size
  8567. * will be derived from the parameters. The precision property is a multiplier allowing
  8568. * rendering at a higher or lower resolution.
  8569. * @param successCallback The callback receives a single parameter which contains the
  8570. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8571. * src parameter of an <img> to display it.
  8572. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8573. * Check your browser for supported MIME types.
  8574. * @param samples Texture samples (default: 1)
  8575. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8576. * @param fileName A name for for the downloaded file.
  8577. * @constructor
  8578. */
  8579. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8580. if (mimeType === void 0) { mimeType = "image/png"; }
  8581. if (samples === void 0) { samples = 1; }
  8582. if (antialiasing === void 0) { antialiasing = false; }
  8583. var width;
  8584. var height;
  8585. //If a precision value is specified
  8586. if (size.precision) {
  8587. width = Math.round(engine.getRenderWidth() * size.precision);
  8588. height = Math.round(width / engine.getAspectRatio(camera));
  8589. size = { width: width, height: height };
  8590. }
  8591. else if (size.width && size.height) {
  8592. width = size.width;
  8593. height = size.height;
  8594. }
  8595. else if (size.width && !size.height) {
  8596. width = size.width;
  8597. height = Math.round(width / engine.getAspectRatio(camera));
  8598. size = { width: width, height: height };
  8599. }
  8600. else if (size.height && !size.width) {
  8601. height = size.height;
  8602. width = Math.round(height * engine.getAspectRatio(camera));
  8603. size = { width: width, height: height };
  8604. }
  8605. else if (!isNaN(size)) {
  8606. height = size;
  8607. width = size;
  8608. }
  8609. else {
  8610. Tools.Error("Invalid 'size' parameter !");
  8611. return;
  8612. }
  8613. var scene = camera.getScene();
  8614. var previousCamera = null;
  8615. if (scene.activeCamera !== camera) {
  8616. previousCamera = scene.activeCamera;
  8617. scene.activeCamera = camera;
  8618. }
  8619. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8620. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8621. texture.renderList = null;
  8622. texture.samples = samples;
  8623. if (antialiasing) {
  8624. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8625. }
  8626. texture.onAfterRenderObservable.add(function () {
  8627. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8628. });
  8629. scene.incrementRenderId();
  8630. scene.resetCachedMaterial();
  8631. texture.render(true);
  8632. texture.dispose();
  8633. if (previousCamera) {
  8634. scene.activeCamera = previousCamera;
  8635. }
  8636. camera.getProjectionMatrix(true); // Force cache refresh;
  8637. };
  8638. // XHR response validator for local file scenario
  8639. Tools.ValidateXHRData = function (xhr, dataType) {
  8640. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8641. if (dataType === void 0) { dataType = 7; }
  8642. try {
  8643. if (dataType & 1) {
  8644. if (xhr.responseText && xhr.responseText.length > 0) {
  8645. return true;
  8646. }
  8647. else if (dataType === 1) {
  8648. return false;
  8649. }
  8650. }
  8651. if (dataType & 2) {
  8652. // Check header width and height since there is no "TGA" magic number
  8653. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8654. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8655. return true;
  8656. }
  8657. else if (dataType === 2) {
  8658. return false;
  8659. }
  8660. }
  8661. if (dataType & 4) {
  8662. // Check for the "DDS" magic number
  8663. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8664. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8665. return true;
  8666. }
  8667. else {
  8668. return false;
  8669. }
  8670. }
  8671. }
  8672. catch (e) {
  8673. // Global protection
  8674. }
  8675. return false;
  8676. };
  8677. /**
  8678. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8679. * Be aware Math.random() could cause collisions, but:
  8680. * "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"
  8681. */
  8682. Tools.RandomId = function () {
  8683. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8684. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8685. return v.toString(16);
  8686. });
  8687. };
  8688. /**
  8689. * Test if the given uri is a base64 string.
  8690. * @param uri The uri to test
  8691. * @return True if the uri is a base64 string or false otherwise.
  8692. */
  8693. Tools.IsBase64 = function (uri) {
  8694. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8695. };
  8696. /**
  8697. * Decode the given base64 uri.
  8698. * @param uri The uri to decode
  8699. * @return The decoded base64 data.
  8700. */
  8701. Tools.DecodeBase64 = function (uri) {
  8702. var decodedString = atob(uri.split(",")[1]);
  8703. var bufferLength = decodedString.length;
  8704. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8705. for (var i = 0; i < bufferLength; i++) {
  8706. bufferView[i] = decodedString.charCodeAt(i);
  8707. }
  8708. return bufferView.buffer;
  8709. };
  8710. Object.defineProperty(Tools, "NoneLogLevel", {
  8711. get: function () {
  8712. return Tools._NoneLogLevel;
  8713. },
  8714. enumerable: true,
  8715. configurable: true
  8716. });
  8717. Object.defineProperty(Tools, "MessageLogLevel", {
  8718. get: function () {
  8719. return Tools._MessageLogLevel;
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. Object.defineProperty(Tools, "WarningLogLevel", {
  8725. get: function () {
  8726. return Tools._WarningLogLevel;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Object.defineProperty(Tools, "ErrorLogLevel", {
  8732. get: function () {
  8733. return Tools._ErrorLogLevel;
  8734. },
  8735. enumerable: true,
  8736. configurable: true
  8737. });
  8738. Object.defineProperty(Tools, "AllLogLevel", {
  8739. get: function () {
  8740. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8741. },
  8742. enumerable: true,
  8743. configurable: true
  8744. });
  8745. Tools._AddLogEntry = function (entry) {
  8746. Tools._LogCache = entry + Tools._LogCache;
  8747. if (Tools.OnNewCacheEntry) {
  8748. Tools.OnNewCacheEntry(entry);
  8749. }
  8750. };
  8751. Tools._FormatMessage = function (message) {
  8752. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8753. var date = new Date();
  8754. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8755. };
  8756. Tools._LogDisabled = function (message) {
  8757. // nothing to do
  8758. };
  8759. Tools._LogEnabled = function (message) {
  8760. var formattedMessage = Tools._FormatMessage(message);
  8761. console.log("BJS - " + formattedMessage);
  8762. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8763. Tools._AddLogEntry(entry);
  8764. };
  8765. Tools._WarnDisabled = function (message) {
  8766. // nothing to do
  8767. };
  8768. Tools._WarnEnabled = function (message) {
  8769. var formattedMessage = Tools._FormatMessage(message);
  8770. console.warn("BJS - " + formattedMessage);
  8771. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8772. Tools._AddLogEntry(entry);
  8773. };
  8774. Tools._ErrorDisabled = function (message) {
  8775. // nothing to do
  8776. };
  8777. Tools._ErrorEnabled = function (message) {
  8778. Tools.errorsCount++;
  8779. var formattedMessage = Tools._FormatMessage(message);
  8780. console.error("BJS - " + formattedMessage);
  8781. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8782. Tools._AddLogEntry(entry);
  8783. };
  8784. Object.defineProperty(Tools, "LogCache", {
  8785. get: function () {
  8786. return Tools._LogCache;
  8787. },
  8788. enumerable: true,
  8789. configurable: true
  8790. });
  8791. Tools.ClearLogCache = function () {
  8792. Tools._LogCache = "";
  8793. Tools.errorsCount = 0;
  8794. };
  8795. Object.defineProperty(Tools, "LogLevels", {
  8796. set: function (level) {
  8797. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8798. Tools.Log = Tools._LogEnabled;
  8799. }
  8800. else {
  8801. Tools.Log = Tools._LogDisabled;
  8802. }
  8803. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8804. Tools.Warn = Tools._WarnEnabled;
  8805. }
  8806. else {
  8807. Tools.Warn = Tools._WarnDisabled;
  8808. }
  8809. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8810. Tools.Error = Tools._ErrorEnabled;
  8811. }
  8812. else {
  8813. Tools.Error = Tools._ErrorDisabled;
  8814. }
  8815. },
  8816. enumerable: true,
  8817. configurable: true
  8818. });
  8819. Tools.IsWindowObjectExist = function () {
  8820. return (typeof window) !== "undefined";
  8821. };
  8822. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8823. get: function () {
  8824. return Tools._PerformanceNoneLogLevel;
  8825. },
  8826. enumerable: true,
  8827. configurable: true
  8828. });
  8829. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8830. get: function () {
  8831. return Tools._PerformanceUserMarkLogLevel;
  8832. },
  8833. enumerable: true,
  8834. configurable: true
  8835. });
  8836. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8837. get: function () {
  8838. return Tools._PerformanceConsoleLogLevel;
  8839. },
  8840. enumerable: true,
  8841. configurable: true
  8842. });
  8843. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8844. set: function (level) {
  8845. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8846. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8847. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8848. return;
  8849. }
  8850. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8851. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8852. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8853. return;
  8854. }
  8855. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8856. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8862. };
  8863. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8864. };
  8865. Tools._StartUserMark = function (counterName, condition) {
  8866. if (condition === void 0) { condition = true; }
  8867. if (!Tools._performance) {
  8868. if (!Tools.IsWindowObjectExist()) {
  8869. return;
  8870. }
  8871. Tools._performance = window.performance;
  8872. }
  8873. if (!condition || !Tools._performance.mark) {
  8874. return;
  8875. }
  8876. Tools._performance.mark(counterName + "-Begin");
  8877. };
  8878. Tools._EndUserMark = function (counterName, condition) {
  8879. if (condition === void 0) { condition = true; }
  8880. if (!condition || !Tools._performance.mark) {
  8881. return;
  8882. }
  8883. Tools._performance.mark(counterName + "-End");
  8884. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8885. };
  8886. Tools._StartPerformanceConsole = function (counterName, condition) {
  8887. if (condition === void 0) { condition = true; }
  8888. if (!condition) {
  8889. return;
  8890. }
  8891. Tools._StartUserMark(counterName, condition);
  8892. if (console.time) {
  8893. console.time(counterName);
  8894. }
  8895. };
  8896. Tools._EndPerformanceConsole = function (counterName, condition) {
  8897. if (condition === void 0) { condition = true; }
  8898. if (!condition) {
  8899. return;
  8900. }
  8901. Tools._EndUserMark(counterName, condition);
  8902. if (console.time) {
  8903. console.timeEnd(counterName);
  8904. }
  8905. };
  8906. Object.defineProperty(Tools, "Now", {
  8907. get: function () {
  8908. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8909. return window.performance.now();
  8910. }
  8911. return new Date().getTime();
  8912. },
  8913. enumerable: true,
  8914. configurable: true
  8915. });
  8916. /**
  8917. * This method will return the name of the class used to create the instance of the given object.
  8918. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8919. * @param object the object to get the class name from
  8920. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8921. */
  8922. Tools.GetClassName = function (object, isType) {
  8923. if (isType === void 0) { isType = false; }
  8924. var name = null;
  8925. if (!isType && object.getClassName) {
  8926. name = object.getClassName();
  8927. }
  8928. else {
  8929. if (object instanceof Object) {
  8930. var classObj = isType ? object : Object.getPrototypeOf(object);
  8931. name = classObj.constructor["__bjsclassName__"];
  8932. }
  8933. if (!name) {
  8934. name = typeof object;
  8935. }
  8936. }
  8937. return name;
  8938. };
  8939. Tools.First = function (array, predicate) {
  8940. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8941. var el = array_1[_i];
  8942. if (predicate(el)) {
  8943. return el;
  8944. }
  8945. }
  8946. return null;
  8947. };
  8948. /**
  8949. * This method will return the name of the full name of the class, including its owning module (if any).
  8950. * 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).
  8951. * @param object the object to get the class name from
  8952. * @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.
  8953. */
  8954. Tools.getFullClassName = function (object, isType) {
  8955. if (isType === void 0) { isType = false; }
  8956. var className = null;
  8957. var moduleName = null;
  8958. if (!isType && object.getClassName) {
  8959. className = object.getClassName();
  8960. }
  8961. else {
  8962. if (object instanceof Object) {
  8963. var classObj = isType ? object : Object.getPrototypeOf(object);
  8964. className = classObj.constructor["__bjsclassName__"];
  8965. moduleName = classObj.constructor["__bjsmoduleName__"];
  8966. }
  8967. if (!className) {
  8968. className = typeof object;
  8969. }
  8970. }
  8971. if (!className) {
  8972. return null;
  8973. }
  8974. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8975. };
  8976. /**
  8977. * 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.
  8978. * @param array
  8979. */
  8980. Tools.arrayOrStringFeeder = function (array) {
  8981. return function (index) {
  8982. if (index >= array.length) {
  8983. return null;
  8984. }
  8985. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8986. if (val && val.getHashCode) {
  8987. val = val.getHashCode();
  8988. }
  8989. if (typeof val === "string") {
  8990. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8991. }
  8992. return val;
  8993. };
  8994. };
  8995. /**
  8996. * Compute the hashCode of a stream of number
  8997. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8998. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8999. * @return the hash code computed
  9000. */
  9001. Tools.hashCodeFromStream = function (feeder) {
  9002. // Based from here: http://stackoverflow.com/a/7616484/802124
  9003. var hash = 0;
  9004. var index = 0;
  9005. var chr = feeder(index++);
  9006. while (chr != null) {
  9007. hash = ((hash << 5) - hash) + chr;
  9008. hash |= 0; // Convert to 32bit integer
  9009. chr = feeder(index++);
  9010. }
  9011. return hash;
  9012. };
  9013. /**
  9014. * Returns a promise that resolves after the given amount of time.
  9015. * @param delay Number of milliseconds to delay
  9016. * @returns Promise that resolves after the given amount of time
  9017. */
  9018. Tools.DelayAsync = function (delay) {
  9019. return new Promise(function (resolve) {
  9020. setTimeout(function () {
  9021. resolve();
  9022. }, delay);
  9023. });
  9024. };
  9025. Tools.BaseUrl = "";
  9026. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9027. /**
  9028. * Default behaviour for cors in the application.
  9029. * It can be a string if the expected behavior is identical in the entire app.
  9030. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9031. */
  9032. Tools.CorsBehavior = "anonymous";
  9033. Tools.UseFallbackTexture = true;
  9034. /**
  9035. * Use this object to register external classes like custom textures or material
  9036. * to allow the laoders to instantiate them
  9037. */
  9038. Tools.RegisteredExternalClasses = {};
  9039. // Used in case of a texture loading problem
  9040. 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";
  9041. Tools.PreprocessUrl = function (url) {
  9042. return url;
  9043. };
  9044. // Logs
  9045. Tools._NoneLogLevel = 0;
  9046. Tools._MessageLogLevel = 1;
  9047. Tools._WarningLogLevel = 2;
  9048. Tools._ErrorLogLevel = 4;
  9049. Tools._LogCache = "";
  9050. Tools.errorsCount = 0;
  9051. Tools.Log = Tools._LogEnabled;
  9052. Tools.Warn = Tools._WarnEnabled;
  9053. Tools.Error = Tools._ErrorEnabled;
  9054. // Performances
  9055. Tools._PerformanceNoneLogLevel = 0;
  9056. Tools._PerformanceUserMarkLogLevel = 1;
  9057. Tools._PerformanceConsoleLogLevel = 2;
  9058. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9059. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9060. return Tools;
  9061. }());
  9062. BABYLON.Tools = Tools;
  9063. /**
  9064. * This class is used to track a performance counter which is number based.
  9065. * The user has access to many properties which give statistics of different nature
  9066. *
  9067. * The implementer can track two kinds of Performance Counter: time and count
  9068. * 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.
  9069. * 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.
  9070. */
  9071. var PerfCounter = /** @class */ (function () {
  9072. function PerfCounter() {
  9073. this._startMonitoringTime = 0;
  9074. this._min = 0;
  9075. this._max = 0;
  9076. this._average = 0;
  9077. this._lastSecAverage = 0;
  9078. this._current = 0;
  9079. this._totalValueCount = 0;
  9080. this._totalAccumulated = 0;
  9081. this._lastSecAccumulated = 0;
  9082. this._lastSecTime = 0;
  9083. this._lastSecValueCount = 0;
  9084. }
  9085. Object.defineProperty(PerfCounter.prototype, "min", {
  9086. /**
  9087. * Returns the smallest value ever
  9088. */
  9089. get: function () {
  9090. return this._min;
  9091. },
  9092. enumerable: true,
  9093. configurable: true
  9094. });
  9095. Object.defineProperty(PerfCounter.prototype, "max", {
  9096. /**
  9097. * Returns the biggest value ever
  9098. */
  9099. get: function () {
  9100. return this._max;
  9101. },
  9102. enumerable: true,
  9103. configurable: true
  9104. });
  9105. Object.defineProperty(PerfCounter.prototype, "average", {
  9106. /**
  9107. * Returns the average value since the performance counter is running
  9108. */
  9109. get: function () {
  9110. return this._average;
  9111. },
  9112. enumerable: true,
  9113. configurable: true
  9114. });
  9115. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9116. /**
  9117. * Returns the average value of the last second the counter was monitored
  9118. */
  9119. get: function () {
  9120. return this._lastSecAverage;
  9121. },
  9122. enumerable: true,
  9123. configurable: true
  9124. });
  9125. Object.defineProperty(PerfCounter.prototype, "current", {
  9126. /**
  9127. * Returns the current value
  9128. */
  9129. get: function () {
  9130. return this._current;
  9131. },
  9132. enumerable: true,
  9133. configurable: true
  9134. });
  9135. Object.defineProperty(PerfCounter.prototype, "total", {
  9136. get: function () {
  9137. return this._totalAccumulated;
  9138. },
  9139. enumerable: true,
  9140. configurable: true
  9141. });
  9142. Object.defineProperty(PerfCounter.prototype, "count", {
  9143. get: function () {
  9144. return this._totalValueCount;
  9145. },
  9146. enumerable: true,
  9147. configurable: true
  9148. });
  9149. /**
  9150. * Call this method to start monitoring a new frame.
  9151. * 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.
  9152. */
  9153. PerfCounter.prototype.fetchNewFrame = function () {
  9154. this._totalValueCount++;
  9155. this._current = 0;
  9156. this._lastSecValueCount++;
  9157. };
  9158. /**
  9159. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9160. * @param newCount the count value to add to the monitored count
  9161. * @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.
  9162. */
  9163. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9164. if (!PerfCounter.Enabled) {
  9165. return;
  9166. }
  9167. this._current += newCount;
  9168. if (fetchResult) {
  9169. this._fetchResult();
  9170. }
  9171. };
  9172. /**
  9173. * Start monitoring this performance counter
  9174. */
  9175. PerfCounter.prototype.beginMonitoring = function () {
  9176. if (!PerfCounter.Enabled) {
  9177. return;
  9178. }
  9179. this._startMonitoringTime = Tools.Now;
  9180. };
  9181. /**
  9182. * Compute the time lapsed since the previous beginMonitoring() call.
  9183. * @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
  9184. */
  9185. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9186. if (newFrame === void 0) { newFrame = true; }
  9187. if (!PerfCounter.Enabled) {
  9188. return;
  9189. }
  9190. if (newFrame) {
  9191. this.fetchNewFrame();
  9192. }
  9193. var currentTime = Tools.Now;
  9194. this._current = currentTime - this._startMonitoringTime;
  9195. if (newFrame) {
  9196. this._fetchResult();
  9197. }
  9198. };
  9199. PerfCounter.prototype._fetchResult = function () {
  9200. this._totalAccumulated += this._current;
  9201. this._lastSecAccumulated += this._current;
  9202. // Min/Max update
  9203. this._min = Math.min(this._min, this._current);
  9204. this._max = Math.max(this._max, this._current);
  9205. this._average = this._totalAccumulated / this._totalValueCount;
  9206. // Reset last sec?
  9207. var now = Tools.Now;
  9208. if ((now - this._lastSecTime) > 1000) {
  9209. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9210. this._lastSecTime = now;
  9211. this._lastSecAccumulated = 0;
  9212. this._lastSecValueCount = 0;
  9213. }
  9214. };
  9215. PerfCounter.Enabled = true;
  9216. return PerfCounter;
  9217. }());
  9218. BABYLON.PerfCounter = PerfCounter;
  9219. /**
  9220. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9221. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9222. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9223. * @param name The name of the class, case should be preserved
  9224. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9225. */
  9226. function className(name, module) {
  9227. return function (target) {
  9228. target["__bjsclassName__"] = name;
  9229. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9230. };
  9231. }
  9232. BABYLON.className = className;
  9233. /**
  9234. * An implementation of a loop for asynchronous functions.
  9235. */
  9236. var AsyncLoop = /** @class */ (function () {
  9237. /**
  9238. * Constroctor.
  9239. * @param iterations the number of iterations.
  9240. * @param _fn the function to run each iteration
  9241. * @param _successCallback the callback that will be called upon succesful execution
  9242. * @param offset starting offset.
  9243. */
  9244. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9245. if (offset === void 0) { offset = 0; }
  9246. this.iterations = iterations;
  9247. this._fn = _fn;
  9248. this._successCallback = _successCallback;
  9249. this.index = offset - 1;
  9250. this._done = false;
  9251. }
  9252. /**
  9253. * Execute the next iteration. Must be called after the last iteration was finished.
  9254. */
  9255. AsyncLoop.prototype.executeNext = function () {
  9256. if (!this._done) {
  9257. if (this.index + 1 < this.iterations) {
  9258. ++this.index;
  9259. this._fn(this);
  9260. }
  9261. else {
  9262. this.breakLoop();
  9263. }
  9264. }
  9265. };
  9266. /**
  9267. * Break the loop and run the success callback.
  9268. */
  9269. AsyncLoop.prototype.breakLoop = function () {
  9270. this._done = true;
  9271. this._successCallback();
  9272. };
  9273. /**
  9274. * Helper function
  9275. */
  9276. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9277. if (offset === void 0) { offset = 0; }
  9278. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9279. loop.executeNext();
  9280. return loop;
  9281. };
  9282. /**
  9283. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9284. * @param iterations total number of iterations
  9285. * @param syncedIterations number of synchronous iterations in each async iteration.
  9286. * @param fn the function to call each iteration.
  9287. * @param callback a success call back that will be called when iterating stops.
  9288. * @param breakFunction a break condition (optional)
  9289. * @param timeout timeout settings for the setTimeout function. default - 0.
  9290. * @constructor
  9291. */
  9292. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9293. if (timeout === void 0) { timeout = 0; }
  9294. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9295. if (breakFunction && breakFunction())
  9296. loop.breakLoop();
  9297. else {
  9298. setTimeout(function () {
  9299. for (var i = 0; i < syncedIterations; ++i) {
  9300. var iteration = (loop.index * syncedIterations) + i;
  9301. if (iteration >= iterations)
  9302. break;
  9303. fn(iteration);
  9304. if (breakFunction && breakFunction()) {
  9305. loop.breakLoop();
  9306. break;
  9307. }
  9308. }
  9309. loop.executeNext();
  9310. }, timeout);
  9311. }
  9312. }, callback);
  9313. };
  9314. return AsyncLoop;
  9315. }());
  9316. BABYLON.AsyncLoop = AsyncLoop;
  9317. })(BABYLON || (BABYLON = {}));
  9318. //# sourceMappingURL=babylon.tools.js.map
  9319. var BABYLON;
  9320. (function (BABYLON) {
  9321. var PromiseStates;
  9322. (function (PromiseStates) {
  9323. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9324. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9325. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9326. })(PromiseStates || (PromiseStates = {}));
  9327. var FulFillmentAgregator = /** @class */ (function () {
  9328. function FulFillmentAgregator() {
  9329. this.count = 0;
  9330. this.target = 0;
  9331. this.results = [];
  9332. }
  9333. return FulFillmentAgregator;
  9334. }());
  9335. var InternalPromise = /** @class */ (function () {
  9336. function InternalPromise(resolver) {
  9337. var _this = this;
  9338. this._state = PromiseStates.Pending;
  9339. this._children = new Array();
  9340. this._rejectWasConsumed = false;
  9341. if (!resolver) {
  9342. return;
  9343. }
  9344. try {
  9345. resolver(function (value) {
  9346. _this._resolve(value);
  9347. }, function (reason) {
  9348. _this._reject(reason);
  9349. });
  9350. }
  9351. catch (e) {
  9352. this._reject(e);
  9353. }
  9354. }
  9355. InternalPromise.prototype.catch = function (onRejected) {
  9356. return this.then(undefined, onRejected);
  9357. };
  9358. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9359. var _this = this;
  9360. var newPromise = new InternalPromise();
  9361. newPromise._onFulfilled = onFulfilled;
  9362. newPromise._onRejected = onRejected;
  9363. // Composition
  9364. this._children.push(newPromise);
  9365. if (this._state !== PromiseStates.Pending) {
  9366. BABYLON.Tools.SetImmediate(function () {
  9367. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9368. var returnedValue = newPromise._resolve(_this._result);
  9369. if (returnedValue !== undefined && returnedValue !== null) {
  9370. if (returnedValue._state !== undefined) {
  9371. var returnedPromise = returnedValue;
  9372. newPromise._children.push(returnedPromise);
  9373. newPromise = returnedPromise;
  9374. }
  9375. else {
  9376. newPromise._result = returnedValue;
  9377. }
  9378. }
  9379. }
  9380. else {
  9381. newPromise._reject(_this._reason);
  9382. }
  9383. });
  9384. }
  9385. return newPromise;
  9386. };
  9387. InternalPromise.prototype._moveChildren = function (children) {
  9388. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9389. if (this._state === PromiseStates.Fulfilled) {
  9390. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9391. var child = _b[_i];
  9392. child._resolve(this._result);
  9393. }
  9394. }
  9395. else if (this._state === PromiseStates.Rejected) {
  9396. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9397. var child = _d[_c];
  9398. child._reject(this._reason);
  9399. }
  9400. }
  9401. var _a;
  9402. };
  9403. InternalPromise.prototype._resolve = function (value) {
  9404. try {
  9405. this._state = PromiseStates.Fulfilled;
  9406. this._result = value;
  9407. var returnedValue = null;
  9408. if (this._onFulfilled) {
  9409. returnedValue = this._onFulfilled(value);
  9410. }
  9411. if (returnedValue !== undefined && returnedValue !== null) {
  9412. if (returnedValue._state !== undefined) {
  9413. // Transmit children
  9414. var returnedPromise = returnedValue;
  9415. returnedPromise._moveChildren(this._children);
  9416. }
  9417. else {
  9418. value = returnedValue;
  9419. }
  9420. }
  9421. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9422. var child = _a[_i];
  9423. child._resolve(value);
  9424. }
  9425. this._children.length = 0;
  9426. delete this._onFulfilled;
  9427. delete this._onRejected;
  9428. return returnedValue;
  9429. }
  9430. catch (e) {
  9431. this._reject(e, true);
  9432. }
  9433. return null;
  9434. };
  9435. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9436. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9437. this._state = PromiseStates.Rejected;
  9438. this._reason = reason;
  9439. if (this._onRejected && !onLocalThrow) {
  9440. try {
  9441. this._onRejected(reason);
  9442. this._rejectWasConsumed = true;
  9443. }
  9444. catch (e) {
  9445. reason = e;
  9446. }
  9447. }
  9448. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9449. var child = _a[_i];
  9450. if (this._rejectWasConsumed) {
  9451. child._resolve(null);
  9452. }
  9453. else {
  9454. child._reject(reason);
  9455. }
  9456. }
  9457. this._children.length = 0;
  9458. delete this._onFulfilled;
  9459. delete this._onRejected;
  9460. };
  9461. InternalPromise.resolve = function (value) {
  9462. var newPromise = new InternalPromise();
  9463. newPromise._resolve(value);
  9464. return newPromise;
  9465. };
  9466. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9467. promise.then(function (value) {
  9468. agregator.results[index] = value;
  9469. agregator.count++;
  9470. if (agregator.count === agregator.target) {
  9471. agregator.rootPromise._resolve(agregator.results);
  9472. }
  9473. return null;
  9474. }, function (reason) {
  9475. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9476. agregator.rootPromise._reject(reason);
  9477. }
  9478. });
  9479. };
  9480. InternalPromise.all = function (promises) {
  9481. var newPromise = new InternalPromise();
  9482. var agregator = new FulFillmentAgregator();
  9483. agregator.target = promises.length;
  9484. agregator.rootPromise = newPromise;
  9485. if (promises.length) {
  9486. for (var index = 0; index < promises.length; index++) {
  9487. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9488. }
  9489. }
  9490. else {
  9491. newPromise._resolve([]);
  9492. }
  9493. return newPromise;
  9494. };
  9495. InternalPromise.race = function (promises) {
  9496. var newPromise = new InternalPromise();
  9497. if (promises.length) {
  9498. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9499. var promise = promises_1[_i];
  9500. promise.then(function (value) {
  9501. if (newPromise) {
  9502. newPromise._resolve(value);
  9503. newPromise = null;
  9504. }
  9505. return null;
  9506. }, function (reason) {
  9507. if (newPromise) {
  9508. newPromise._reject(reason);
  9509. newPromise = null;
  9510. }
  9511. });
  9512. }
  9513. }
  9514. return newPromise;
  9515. };
  9516. return InternalPromise;
  9517. }());
  9518. /**
  9519. * Helper class that provides a small promise polyfill
  9520. */
  9521. var PromisePolyfill = /** @class */ (function () {
  9522. function PromisePolyfill() {
  9523. }
  9524. /**
  9525. * Static function used to check if the polyfill is required
  9526. * If this is the case then the function will inject the polyfill to window.Promise
  9527. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9528. */
  9529. PromisePolyfill.Apply = function (force) {
  9530. if (force === void 0) { force = false; }
  9531. if (force || typeof Promise === 'undefined') {
  9532. var root = window;
  9533. root.Promise = InternalPromise;
  9534. }
  9535. };
  9536. return PromisePolyfill;
  9537. }());
  9538. BABYLON.PromisePolyfill = PromisePolyfill;
  9539. })(BABYLON || (BABYLON = {}));
  9540. //# sourceMappingURL=babylon.promise.js.map
  9541. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9542. var BABYLON;
  9543. (function (BABYLON) {
  9544. /**
  9545. * Helper class to push actions to a pool of workers.
  9546. */
  9547. var WorkerPool = /** @class */ (function () {
  9548. /**
  9549. * Constructor
  9550. * @param workers Array of workers to use for actions
  9551. */
  9552. function WorkerPool(workers) {
  9553. this._pendingActions = new Array();
  9554. this._workerInfos = workers.map(function (worker) { return ({
  9555. worker: worker,
  9556. active: false
  9557. }); });
  9558. }
  9559. /**
  9560. * Terminates all workers and clears any pending actions.
  9561. */
  9562. WorkerPool.prototype.dispose = function () {
  9563. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9564. var workerInfo = _a[_i];
  9565. workerInfo.worker.terminate();
  9566. }
  9567. delete this._workerInfos;
  9568. delete this._pendingActions;
  9569. };
  9570. /**
  9571. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9572. * pended until a worker has completed its action.
  9573. * @param action The action to perform. Call onComplete when the action is complete.
  9574. */
  9575. WorkerPool.prototype.push = function (action) {
  9576. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9577. var workerInfo = _a[_i];
  9578. if (!workerInfo.active) {
  9579. this._execute(workerInfo, action);
  9580. return;
  9581. }
  9582. }
  9583. this._pendingActions.push(action);
  9584. };
  9585. WorkerPool.prototype._execute = function (workerInfo, action) {
  9586. var _this = this;
  9587. workerInfo.active = true;
  9588. action(workerInfo.worker, function () {
  9589. workerInfo.active = false;
  9590. var nextAction = _this._pendingActions.shift();
  9591. if (nextAction) {
  9592. _this._execute(workerInfo, nextAction);
  9593. }
  9594. });
  9595. };
  9596. return WorkerPool;
  9597. }());
  9598. BABYLON.WorkerPool = WorkerPool;
  9599. })(BABYLON || (BABYLON = {}));
  9600. //# sourceMappingURL=babylon.workerPool.js.map
  9601. var BABYLON;
  9602. (function (BABYLON) {
  9603. var _AlphaState = /** @class */ (function () {
  9604. /**
  9605. * Initializes the state.
  9606. */
  9607. function _AlphaState() {
  9608. this._isAlphaBlendDirty = false;
  9609. this._isBlendFunctionParametersDirty = false;
  9610. this._isBlendEquationParametersDirty = false;
  9611. this._isBlendConstantsDirty = false;
  9612. this._alphaBlend = false;
  9613. this._blendFunctionParameters = new Array(4);
  9614. this._blendEquationParameters = new Array(2);
  9615. this._blendConstants = new Array(4);
  9616. this.reset();
  9617. }
  9618. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9619. get: function () {
  9620. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9626. get: function () {
  9627. return this._alphaBlend;
  9628. },
  9629. set: function (value) {
  9630. if (this._alphaBlend === value) {
  9631. return;
  9632. }
  9633. this._alphaBlend = value;
  9634. this._isAlphaBlendDirty = true;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9640. if (this._blendConstants[0] === r &&
  9641. this._blendConstants[1] === g &&
  9642. this._blendConstants[2] === b &&
  9643. this._blendConstants[3] === a) {
  9644. return;
  9645. }
  9646. this._blendConstants[0] = r;
  9647. this._blendConstants[1] = g;
  9648. this._blendConstants[2] = b;
  9649. this._blendConstants[3] = a;
  9650. this._isBlendConstantsDirty = true;
  9651. };
  9652. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9653. if (this._blendFunctionParameters[0] === value0 &&
  9654. this._blendFunctionParameters[1] === value1 &&
  9655. this._blendFunctionParameters[2] === value2 &&
  9656. this._blendFunctionParameters[3] === value3) {
  9657. return;
  9658. }
  9659. this._blendFunctionParameters[0] = value0;
  9660. this._blendFunctionParameters[1] = value1;
  9661. this._blendFunctionParameters[2] = value2;
  9662. this._blendFunctionParameters[3] = value3;
  9663. this._isBlendFunctionParametersDirty = true;
  9664. };
  9665. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9666. if (this._blendEquationParameters[0] === rgb &&
  9667. this._blendEquationParameters[1] === alpha) {
  9668. return;
  9669. }
  9670. this._blendEquationParameters[0] = rgb;
  9671. this._blendEquationParameters[1] = alpha;
  9672. this._isBlendEquationParametersDirty = true;
  9673. };
  9674. _AlphaState.prototype.reset = function () {
  9675. this._alphaBlend = false;
  9676. this._blendFunctionParameters[0] = null;
  9677. this._blendFunctionParameters[1] = null;
  9678. this._blendFunctionParameters[2] = null;
  9679. this._blendFunctionParameters[3] = null;
  9680. this._blendEquationParameters[0] = null;
  9681. this._blendEquationParameters[1] = null;
  9682. this._blendConstants[0] = null;
  9683. this._blendConstants[1] = null;
  9684. this._blendConstants[2] = null;
  9685. this._blendConstants[3] = null;
  9686. this._isAlphaBlendDirty = true;
  9687. this._isBlendFunctionParametersDirty = false;
  9688. this._isBlendEquationParametersDirty = false;
  9689. this._isBlendConstantsDirty = false;
  9690. };
  9691. _AlphaState.prototype.apply = function (gl) {
  9692. if (!this.isDirty) {
  9693. return;
  9694. }
  9695. // Alpha blend
  9696. if (this._isAlphaBlendDirty) {
  9697. if (this._alphaBlend) {
  9698. gl.enable(gl.BLEND);
  9699. }
  9700. else {
  9701. gl.disable(gl.BLEND);
  9702. }
  9703. this._isAlphaBlendDirty = false;
  9704. }
  9705. // Alpha function
  9706. if (this._isBlendFunctionParametersDirty) {
  9707. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9708. this._isBlendFunctionParametersDirty = false;
  9709. }
  9710. // Alpha equation
  9711. if (this._isBlendEquationParametersDirty) {
  9712. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9713. this._isBlendEquationParametersDirty = false;
  9714. }
  9715. // Constants
  9716. if (this._isBlendConstantsDirty) {
  9717. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9718. this._isBlendConstantsDirty = false;
  9719. }
  9720. };
  9721. return _AlphaState;
  9722. }());
  9723. BABYLON._AlphaState = _AlphaState;
  9724. })(BABYLON || (BABYLON = {}));
  9725. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9726. var BABYLON;
  9727. (function (BABYLON) {
  9728. var _DepthCullingState = /** @class */ (function () {
  9729. /**
  9730. * Initializes the state.
  9731. */
  9732. function _DepthCullingState() {
  9733. this._isDepthTestDirty = false;
  9734. this._isDepthMaskDirty = false;
  9735. this._isDepthFuncDirty = false;
  9736. this._isCullFaceDirty = false;
  9737. this._isCullDirty = false;
  9738. this._isZOffsetDirty = false;
  9739. this._isFrontFaceDirty = false;
  9740. this.reset();
  9741. }
  9742. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9743. get: function () {
  9744. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9745. },
  9746. enumerable: true,
  9747. configurable: true
  9748. });
  9749. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9750. get: function () {
  9751. return this._zOffset;
  9752. },
  9753. set: function (value) {
  9754. if (this._zOffset === value) {
  9755. return;
  9756. }
  9757. this._zOffset = value;
  9758. this._isZOffsetDirty = true;
  9759. },
  9760. enumerable: true,
  9761. configurable: true
  9762. });
  9763. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9764. get: function () {
  9765. return this._cullFace;
  9766. },
  9767. set: function (value) {
  9768. if (this._cullFace === value) {
  9769. return;
  9770. }
  9771. this._cullFace = value;
  9772. this._isCullFaceDirty = true;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9778. get: function () {
  9779. return this._cull;
  9780. },
  9781. set: function (value) {
  9782. if (this._cull === value) {
  9783. return;
  9784. }
  9785. this._cull = value;
  9786. this._isCullDirty = true;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9792. get: function () {
  9793. return this._depthFunc;
  9794. },
  9795. set: function (value) {
  9796. if (this._depthFunc === value) {
  9797. return;
  9798. }
  9799. this._depthFunc = value;
  9800. this._isDepthFuncDirty = true;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9806. get: function () {
  9807. return this._depthMask;
  9808. },
  9809. set: function (value) {
  9810. if (this._depthMask === value) {
  9811. return;
  9812. }
  9813. this._depthMask = value;
  9814. this._isDepthMaskDirty = true;
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9820. get: function () {
  9821. return this._depthTest;
  9822. },
  9823. set: function (value) {
  9824. if (this._depthTest === value) {
  9825. return;
  9826. }
  9827. this._depthTest = value;
  9828. this._isDepthTestDirty = true;
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9834. get: function () {
  9835. return this._frontFace;
  9836. },
  9837. set: function (value) {
  9838. if (this._frontFace === value) {
  9839. return;
  9840. }
  9841. this._frontFace = value;
  9842. this._isFrontFaceDirty = true;
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. _DepthCullingState.prototype.reset = function () {
  9848. this._depthMask = true;
  9849. this._depthTest = true;
  9850. this._depthFunc = null;
  9851. this._cullFace = null;
  9852. this._cull = null;
  9853. this._zOffset = 0;
  9854. this._frontFace = null;
  9855. this._isDepthTestDirty = true;
  9856. this._isDepthMaskDirty = true;
  9857. this._isDepthFuncDirty = false;
  9858. this._isCullFaceDirty = false;
  9859. this._isCullDirty = false;
  9860. this._isZOffsetDirty = false;
  9861. this._isFrontFaceDirty = false;
  9862. };
  9863. _DepthCullingState.prototype.apply = function (gl) {
  9864. if (!this.isDirty) {
  9865. return;
  9866. }
  9867. // Cull
  9868. if (this._isCullDirty) {
  9869. if (this.cull) {
  9870. gl.enable(gl.CULL_FACE);
  9871. }
  9872. else {
  9873. gl.disable(gl.CULL_FACE);
  9874. }
  9875. this._isCullDirty = false;
  9876. }
  9877. // Cull face
  9878. if (this._isCullFaceDirty) {
  9879. gl.cullFace(this.cullFace);
  9880. this._isCullFaceDirty = false;
  9881. }
  9882. // Depth mask
  9883. if (this._isDepthMaskDirty) {
  9884. gl.depthMask(this.depthMask);
  9885. this._isDepthMaskDirty = false;
  9886. }
  9887. // Depth test
  9888. if (this._isDepthTestDirty) {
  9889. if (this.depthTest) {
  9890. gl.enable(gl.DEPTH_TEST);
  9891. }
  9892. else {
  9893. gl.disable(gl.DEPTH_TEST);
  9894. }
  9895. this._isDepthTestDirty = false;
  9896. }
  9897. // Depth func
  9898. if (this._isDepthFuncDirty) {
  9899. gl.depthFunc(this.depthFunc);
  9900. this._isDepthFuncDirty = false;
  9901. }
  9902. // zOffset
  9903. if (this._isZOffsetDirty) {
  9904. if (this.zOffset) {
  9905. gl.enable(gl.POLYGON_OFFSET_FILL);
  9906. gl.polygonOffset(this.zOffset, 0);
  9907. }
  9908. else {
  9909. gl.disable(gl.POLYGON_OFFSET_FILL);
  9910. }
  9911. this._isZOffsetDirty = false;
  9912. }
  9913. // Front face
  9914. if (this._isFrontFaceDirty) {
  9915. gl.frontFace(this.frontFace);
  9916. this._isFrontFaceDirty = false;
  9917. }
  9918. };
  9919. return _DepthCullingState;
  9920. }());
  9921. BABYLON._DepthCullingState = _DepthCullingState;
  9922. })(BABYLON || (BABYLON = {}));
  9923. //# sourceMappingURL=babylon.depthCullingState.js.map
  9924. var BABYLON;
  9925. (function (BABYLON) {
  9926. var _StencilState = /** @class */ (function () {
  9927. function _StencilState() {
  9928. this._isStencilTestDirty = false;
  9929. this._isStencilMaskDirty = false;
  9930. this._isStencilFuncDirty = false;
  9931. this._isStencilOpDirty = false;
  9932. this.reset();
  9933. }
  9934. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9935. get: function () {
  9936. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9942. get: function () {
  9943. return this._stencilFunc;
  9944. },
  9945. set: function (value) {
  9946. if (this._stencilFunc === value) {
  9947. return;
  9948. }
  9949. this._stencilFunc = value;
  9950. this._isStencilFuncDirty = true;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9956. get: function () {
  9957. return this._stencilFuncRef;
  9958. },
  9959. set: function (value) {
  9960. if (this._stencilFuncRef === value) {
  9961. return;
  9962. }
  9963. this._stencilFuncRef = value;
  9964. this._isStencilFuncDirty = true;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9970. get: function () {
  9971. return this._stencilFuncMask;
  9972. },
  9973. set: function (value) {
  9974. if (this._stencilFuncMask === value) {
  9975. return;
  9976. }
  9977. this._stencilFuncMask = value;
  9978. this._isStencilFuncDirty = true;
  9979. },
  9980. enumerable: true,
  9981. configurable: true
  9982. });
  9983. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9984. get: function () {
  9985. return this._stencilOpStencilFail;
  9986. },
  9987. set: function (value) {
  9988. if (this._stencilOpStencilFail === value) {
  9989. return;
  9990. }
  9991. this._stencilOpStencilFail = value;
  9992. this._isStencilOpDirty = true;
  9993. },
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9998. get: function () {
  9999. return this._stencilOpDepthFail;
  10000. },
  10001. set: function (value) {
  10002. if (this._stencilOpDepthFail === value) {
  10003. return;
  10004. }
  10005. this._stencilOpDepthFail = value;
  10006. this._isStencilOpDirty = true;
  10007. },
  10008. enumerable: true,
  10009. configurable: true
  10010. });
  10011. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10012. get: function () {
  10013. return this._stencilOpStencilDepthPass;
  10014. },
  10015. set: function (value) {
  10016. if (this._stencilOpStencilDepthPass === value) {
  10017. return;
  10018. }
  10019. this._stencilOpStencilDepthPass = value;
  10020. this._isStencilOpDirty = true;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10026. get: function () {
  10027. return this._stencilMask;
  10028. },
  10029. set: function (value) {
  10030. if (this._stencilMask === value) {
  10031. return;
  10032. }
  10033. this._stencilMask = value;
  10034. this._isStencilMaskDirty = true;
  10035. },
  10036. enumerable: true,
  10037. configurable: true
  10038. });
  10039. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10040. get: function () {
  10041. return this._stencilTest;
  10042. },
  10043. set: function (value) {
  10044. if (this._stencilTest === value) {
  10045. return;
  10046. }
  10047. this._stencilTest = value;
  10048. this._isStencilTestDirty = true;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. _StencilState.prototype.reset = function () {
  10054. this._stencilTest = false;
  10055. this._stencilMask = 0xFF;
  10056. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10057. this._stencilFuncRef = 1;
  10058. this._stencilFuncMask = 0xFF;
  10059. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10060. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10061. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10062. this._isStencilTestDirty = true;
  10063. this._isStencilMaskDirty = true;
  10064. this._isStencilFuncDirty = true;
  10065. this._isStencilOpDirty = true;
  10066. };
  10067. _StencilState.prototype.apply = function (gl) {
  10068. if (!this.isDirty) {
  10069. return;
  10070. }
  10071. // Stencil test
  10072. if (this._isStencilTestDirty) {
  10073. if (this.stencilTest) {
  10074. gl.enable(gl.STENCIL_TEST);
  10075. }
  10076. else {
  10077. gl.disable(gl.STENCIL_TEST);
  10078. }
  10079. this._isStencilTestDirty = false;
  10080. }
  10081. // Stencil mask
  10082. if (this._isStencilMaskDirty) {
  10083. gl.stencilMask(this.stencilMask);
  10084. this._isStencilMaskDirty = false;
  10085. }
  10086. // Stencil func
  10087. if (this._isStencilFuncDirty) {
  10088. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10089. this._isStencilFuncDirty = false;
  10090. }
  10091. // Stencil op
  10092. if (this._isStencilOpDirty) {
  10093. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10094. this._isStencilOpDirty = false;
  10095. }
  10096. };
  10097. return _StencilState;
  10098. }());
  10099. BABYLON._StencilState = _StencilState;
  10100. })(BABYLON || (BABYLON = {}));
  10101. //# sourceMappingURL=babylon.stencilState.js.map
  10102. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10103. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10104. s = arguments[i];
  10105. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10106. t[p] = s[p];
  10107. }
  10108. return t;
  10109. };
  10110. var BABYLON;
  10111. (function (BABYLON) {
  10112. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10113. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10114. };
  10115. var compileRawShader = function (gl, source, type) {
  10116. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10117. gl.shaderSource(shader, source);
  10118. gl.compileShader(shader);
  10119. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10120. var log = gl.getShaderInfoLog(shader);
  10121. if (log) {
  10122. throw new Error(log);
  10123. }
  10124. }
  10125. if (!shader) {
  10126. throw new Error("Something went wrong while compile the shader.");
  10127. }
  10128. return shader;
  10129. };
  10130. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10131. var magFilter = gl.NEAREST;
  10132. var minFilter = gl.NEAREST;
  10133. switch (samplingMode) {
  10134. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10135. magFilter = gl.LINEAR;
  10136. if (generateMipMaps) {
  10137. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10138. }
  10139. else {
  10140. minFilter = gl.LINEAR;
  10141. }
  10142. break;
  10143. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10144. magFilter = gl.LINEAR;
  10145. if (generateMipMaps) {
  10146. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10147. }
  10148. else {
  10149. minFilter = gl.LINEAR;
  10150. }
  10151. break;
  10152. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10153. magFilter = gl.NEAREST;
  10154. if (generateMipMaps) {
  10155. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10156. }
  10157. else {
  10158. minFilter = gl.NEAREST;
  10159. }
  10160. break;
  10161. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10162. magFilter = gl.NEAREST;
  10163. if (generateMipMaps) {
  10164. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10165. }
  10166. else {
  10167. minFilter = gl.NEAREST;
  10168. }
  10169. break;
  10170. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10171. magFilter = gl.NEAREST;
  10172. if (generateMipMaps) {
  10173. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10174. }
  10175. else {
  10176. minFilter = gl.LINEAR;
  10177. }
  10178. break;
  10179. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10180. magFilter = gl.NEAREST;
  10181. if (generateMipMaps) {
  10182. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10183. }
  10184. else {
  10185. minFilter = gl.LINEAR;
  10186. }
  10187. break;
  10188. case BABYLON.Texture.NEAREST_LINEAR:
  10189. magFilter = gl.NEAREST;
  10190. minFilter = gl.LINEAR;
  10191. break;
  10192. case BABYLON.Texture.NEAREST_NEAREST:
  10193. magFilter = gl.NEAREST;
  10194. minFilter = gl.NEAREST;
  10195. break;
  10196. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10197. magFilter = gl.LINEAR;
  10198. if (generateMipMaps) {
  10199. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10200. }
  10201. else {
  10202. minFilter = gl.NEAREST;
  10203. }
  10204. break;
  10205. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10206. magFilter = gl.LINEAR;
  10207. if (generateMipMaps) {
  10208. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10209. }
  10210. else {
  10211. minFilter = gl.NEAREST;
  10212. }
  10213. break;
  10214. case BABYLON.Texture.LINEAR_LINEAR:
  10215. magFilter = gl.LINEAR;
  10216. minFilter = gl.LINEAR;
  10217. break;
  10218. case BABYLON.Texture.LINEAR_NEAREST:
  10219. magFilter = gl.LINEAR;
  10220. minFilter = gl.NEAREST;
  10221. break;
  10222. }
  10223. return {
  10224. min: minFilter,
  10225. mag: magFilter
  10226. };
  10227. };
  10228. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10229. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10230. var img;
  10231. var onload = function () {
  10232. loadedImages[index] = img;
  10233. loadedImages._internalCount++;
  10234. if (scene) {
  10235. scene._removePendingData(img);
  10236. }
  10237. if (loadedImages._internalCount === 6) {
  10238. onfinish(loadedImages);
  10239. }
  10240. };
  10241. var onerror = function (message, exception) {
  10242. if (scene) {
  10243. scene._removePendingData(img);
  10244. }
  10245. if (onErrorCallBack) {
  10246. onErrorCallBack(message, exception);
  10247. }
  10248. };
  10249. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10250. if (scene) {
  10251. scene._addPendingData(img);
  10252. }
  10253. };
  10254. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10255. if (onError === void 0) { onError = null; }
  10256. var loadedImages = [];
  10257. loadedImages._internalCount = 0;
  10258. for (var index = 0; index < 6; index++) {
  10259. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10260. }
  10261. };
  10262. var BufferPointer = /** @class */ (function () {
  10263. function BufferPointer() {
  10264. }
  10265. return BufferPointer;
  10266. }());
  10267. var InstancingAttributeInfo = /** @class */ (function () {
  10268. function InstancingAttributeInfo() {
  10269. }
  10270. return InstancingAttributeInfo;
  10271. }());
  10272. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10273. /**
  10274. * Define options used to create a render target texture
  10275. */
  10276. var RenderTargetCreationOptions = /** @class */ (function () {
  10277. function RenderTargetCreationOptions() {
  10278. }
  10279. return RenderTargetCreationOptions;
  10280. }());
  10281. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10282. /**
  10283. * Define options used to create a depth texture
  10284. */
  10285. var DepthTextureCreationOptions = /** @class */ (function () {
  10286. function DepthTextureCreationOptions() {
  10287. }
  10288. return DepthTextureCreationOptions;
  10289. }());
  10290. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10291. /**
  10292. * Regroup several parameters relative to the browser in use
  10293. */
  10294. var EngineCapabilities = /** @class */ (function () {
  10295. function EngineCapabilities() {
  10296. }
  10297. return EngineCapabilities;
  10298. }());
  10299. BABYLON.EngineCapabilities = EngineCapabilities;
  10300. /**
  10301. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10302. */
  10303. var Engine = /** @class */ (function () {
  10304. /**
  10305. * @constructor
  10306. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10307. * @param antialias defines enable antialiasing (default: false)
  10308. * @param options defines further options to be sent to the getContext() function
  10309. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10310. */
  10311. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10312. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10313. var _this = this;
  10314. // Public members
  10315. this.forcePOTTextures = false;
  10316. this.isFullscreen = false;
  10317. this.isPointerLock = false;
  10318. this.cullBackFaces = true;
  10319. this.renderEvenInBackground = true;
  10320. this.preventCacheWipeBetweenFrames = false;
  10321. // To enable/disable IDB support and avoid XHR on .manifest
  10322. this.enableOfflineSupport = false;
  10323. this.scenes = new Array();
  10324. this.postProcesses = new Array();
  10325. // Observables
  10326. /**
  10327. * Observable event triggered each time the rendering canvas is resized
  10328. */
  10329. this.onResizeObservable = new BABYLON.Observable();
  10330. /**
  10331. * Observable event triggered each time the canvas loses focus
  10332. */
  10333. this.onCanvasBlurObservable = new BABYLON.Observable();
  10334. /**
  10335. * Observable event triggered each time the canvas gains focus
  10336. */
  10337. this.onCanvasFocusObservable = new BABYLON.Observable();
  10338. /**
  10339. * Observable event triggered each time the canvas receives pointerout event
  10340. */
  10341. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10342. /**
  10343. * Observable event triggered before each texture is initialized
  10344. */
  10345. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10346. //WebVR
  10347. this._vrDisplay = undefined;
  10348. this._vrSupported = false;
  10349. this._vrExclusivePointerMode = false;
  10350. // Uniform buffers list
  10351. this.disableUniformBuffers = false;
  10352. this._uniformBuffers = new Array();
  10353. // Observables
  10354. /**
  10355. * Observable raised when the engine begins a new frame
  10356. */
  10357. this.onBeginFrameObservable = new BABYLON.Observable();
  10358. /**
  10359. * Observable raised when the engine ends the current frame
  10360. */
  10361. this.onEndFrameObservable = new BABYLON.Observable();
  10362. /**
  10363. * Observable raised when the engine is about to compile a shader
  10364. */
  10365. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10366. /**
  10367. * Observable raised when the engine has jsut compiled a shader
  10368. */
  10369. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10370. this._windowIsBackground = false;
  10371. this._webGLVersion = 1.0;
  10372. this._badOS = false;
  10373. this._badDesktopOS = false;
  10374. /**
  10375. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10376. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10377. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10378. */
  10379. this.disableTextureBindingOptimization = false;
  10380. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10381. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10382. this.onVRRequestPresentStart = new BABYLON.Observable();
  10383. this._colorWrite = true;
  10384. this._drawCalls = new BABYLON.PerfCounter();
  10385. this._textureCollisions = new BABYLON.PerfCounter();
  10386. this._renderingQueueLaunched = false;
  10387. this._activeRenderLoops = new Array();
  10388. // Deterministic lockstepMaxSteps
  10389. this._deterministicLockstep = false;
  10390. this._lockstepMaxSteps = 4;
  10391. // Lost context
  10392. this.onContextLostObservable = new BABYLON.Observable();
  10393. this.onContextRestoredObservable = new BABYLON.Observable();
  10394. this._contextWasLost = false;
  10395. this._doNotHandleContextLost = false;
  10396. // FPS
  10397. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10398. this._fps = 60;
  10399. this._deltaTime = 0;
  10400. /**
  10401. * Turn this value on if you want to pause FPS computation when in background
  10402. */
  10403. this.disablePerformanceMonitorInBackground = false;
  10404. // States
  10405. this._depthCullingState = new BABYLON._DepthCullingState();
  10406. this._stencilState = new BABYLON._StencilState();
  10407. this._alphaState = new BABYLON._AlphaState();
  10408. this._alphaMode = Engine.ALPHA_DISABLE;
  10409. // Cache
  10410. this._internalTexturesCache = new Array();
  10411. this._activeChannel = 0;
  10412. this._currentTextureChannel = -1;
  10413. this._boundTexturesCache = {};
  10414. this._compiledEffects = {};
  10415. this._vertexAttribArraysEnabled = [];
  10416. this._uintIndicesCurrentlySet = false;
  10417. this._currentBoundBuffer = new Array();
  10418. this._currentBufferPointers = new Array();
  10419. this._currentInstanceLocations = new Array();
  10420. this._currentInstanceBuffers = new Array();
  10421. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10422. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10423. this._vaoRecordInProgress = false;
  10424. this._mustWipeVertexAttributes = false;
  10425. this._nextFreeTextureSlots = new Array();
  10426. this._maxSimultaneousTextures = 0;
  10427. this._activeRequests = new Array();
  10428. // Hardware supported Compressed Textures
  10429. this._texturesSupported = new Array();
  10430. this._onVRFullScreenTriggered = function () {
  10431. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10432. //get the old size before we change
  10433. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10434. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10435. //get the width and height, change the render size
  10436. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10437. _this.setHardwareScalingLevel(1);
  10438. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10439. }
  10440. else {
  10441. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10442. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10443. }
  10444. };
  10445. this._boundUniforms = {};
  10446. // Register promises
  10447. BABYLON.PromisePolyfill.Apply();
  10448. var canvas = null;
  10449. Engine.Instances.push(this);
  10450. if (!canvasOrContext) {
  10451. return;
  10452. }
  10453. options = options || {};
  10454. if (canvasOrContext.getContext) {
  10455. canvas = canvasOrContext;
  10456. this._renderingCanvas = canvas;
  10457. if (antialias != null) {
  10458. options.antialias = antialias;
  10459. }
  10460. if (options.deterministicLockstep === undefined) {
  10461. options.deterministicLockstep = false;
  10462. }
  10463. if (options.lockstepMaxSteps === undefined) {
  10464. options.lockstepMaxSteps = 4;
  10465. }
  10466. if (options.preserveDrawingBuffer === undefined) {
  10467. options.preserveDrawingBuffer = false;
  10468. }
  10469. if (options.audioEngine === undefined) {
  10470. options.audioEngine = true;
  10471. }
  10472. if (options.stencil === undefined) {
  10473. options.stencil = true;
  10474. }
  10475. this._deterministicLockstep = options.deterministicLockstep;
  10476. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10477. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10478. // Exceptions
  10479. if (navigator && navigator.userAgent) {
  10480. var ua = navigator.userAgent;
  10481. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10482. var exception = _a[_i];
  10483. var key = exception.key;
  10484. var targets = exception.targets;
  10485. if (ua.indexOf(key) > -1) {
  10486. if (exception.capture && exception.captureConstraint) {
  10487. var capture = exception.capture;
  10488. var constraint = exception.captureConstraint;
  10489. var regex = new RegExp(capture);
  10490. var matches = regex.exec(ua);
  10491. if (matches && matches.length > 0) {
  10492. var capturedValue = parseInt(matches[matches.length - 1]);
  10493. if (capturedValue >= constraint) {
  10494. continue;
  10495. }
  10496. }
  10497. }
  10498. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10499. var target = targets_1[_b];
  10500. switch (target) {
  10501. case "uniformBuffer":
  10502. this.disableUniformBuffers = true;
  10503. break;
  10504. case "textureBindingOptimization":
  10505. this.disableTextureBindingOptimization = true;
  10506. break;
  10507. }
  10508. }
  10509. break;
  10510. }
  10511. }
  10512. }
  10513. // GL
  10514. if (!options.disableWebGL2Support) {
  10515. try {
  10516. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10517. if (this._gl) {
  10518. this._webGLVersion = 2.0;
  10519. }
  10520. }
  10521. catch (e) {
  10522. // Do nothing
  10523. }
  10524. }
  10525. if (!this._gl) {
  10526. if (!canvas) {
  10527. throw new Error("The provided canvas is null or undefined.");
  10528. }
  10529. try {
  10530. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10531. }
  10532. catch (e) {
  10533. throw new Error("WebGL not supported");
  10534. }
  10535. }
  10536. if (!this._gl) {
  10537. throw new Error("WebGL not supported");
  10538. }
  10539. this._onCanvasFocus = function () {
  10540. _this.onCanvasFocusObservable.notifyObservers(_this);
  10541. };
  10542. this._onCanvasBlur = function () {
  10543. _this.onCanvasBlurObservable.notifyObservers(_this);
  10544. };
  10545. canvas.addEventListener("focus", this._onCanvasFocus);
  10546. canvas.addEventListener("blur", this._onCanvasBlur);
  10547. this._onBlur = function () {
  10548. if (_this.disablePerformanceMonitorInBackground) {
  10549. _this._performanceMonitor.disable();
  10550. }
  10551. _this._windowIsBackground = true;
  10552. };
  10553. this._onFocus = function () {
  10554. if (_this.disablePerformanceMonitorInBackground) {
  10555. _this._performanceMonitor.enable();
  10556. }
  10557. _this._windowIsBackground = false;
  10558. };
  10559. this._onCanvasPointerOut = function (ev) {
  10560. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10561. };
  10562. window.addEventListener("blur", this._onBlur);
  10563. window.addEventListener("focus", this._onFocus);
  10564. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10565. // Context lost
  10566. if (!this._doNotHandleContextLost) {
  10567. this._onContextLost = function (evt) {
  10568. evt.preventDefault();
  10569. _this._contextWasLost = true;
  10570. BABYLON.Tools.Warn("WebGL context lost.");
  10571. _this.onContextLostObservable.notifyObservers(_this);
  10572. };
  10573. this._onContextRestored = function (evt) {
  10574. // Adding a timeout to avoid race condition at browser level
  10575. setTimeout(function () {
  10576. // Rebuild gl context
  10577. _this._initGLContext();
  10578. // Rebuild effects
  10579. _this._rebuildEffects();
  10580. // Rebuild textures
  10581. _this._rebuildInternalTextures();
  10582. // Rebuild buffers
  10583. _this._rebuildBuffers();
  10584. // Cache
  10585. _this.wipeCaches(true);
  10586. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10587. _this.onContextRestoredObservable.notifyObservers(_this);
  10588. _this._contextWasLost = false;
  10589. }, 0);
  10590. };
  10591. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10592. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10593. }
  10594. }
  10595. else {
  10596. this._gl = canvasOrContext;
  10597. this._renderingCanvas = this._gl.canvas;
  10598. if (this._gl.renderbufferStorageMultisample) {
  10599. this._webGLVersion = 2.0;
  10600. }
  10601. options.stencil = this._gl.getContextAttributes().stencil;
  10602. }
  10603. // Viewport
  10604. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10605. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10606. this.resize();
  10607. this._isStencilEnable = options.stencil ? true : false;
  10608. this._initGLContext();
  10609. if (canvas) {
  10610. // Fullscreen
  10611. this._onFullscreenChange = function () {
  10612. if (document.fullscreen !== undefined) {
  10613. _this.isFullscreen = document.fullscreen;
  10614. }
  10615. else if (document.mozFullScreen !== undefined) {
  10616. _this.isFullscreen = document.mozFullScreen;
  10617. }
  10618. else if (document.webkitIsFullScreen !== undefined) {
  10619. _this.isFullscreen = document.webkitIsFullScreen;
  10620. }
  10621. else if (document.msIsFullScreen !== undefined) {
  10622. _this.isFullscreen = document.msIsFullScreen;
  10623. }
  10624. // Pointer lock
  10625. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10626. canvas.requestPointerLock = canvas.requestPointerLock ||
  10627. canvas.msRequestPointerLock ||
  10628. canvas.mozRequestPointerLock ||
  10629. canvas.webkitRequestPointerLock;
  10630. if (canvas.requestPointerLock) {
  10631. canvas.requestPointerLock();
  10632. }
  10633. }
  10634. };
  10635. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10636. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10637. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10638. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10639. // Pointer lock
  10640. this._onPointerLockChange = function () {
  10641. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10642. document.webkitPointerLockElement === canvas ||
  10643. document.msPointerLockElement === canvas ||
  10644. document.pointerLockElement === canvas);
  10645. };
  10646. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10647. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10648. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10649. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10650. this._onVRDisplayPointerRestricted = function () {
  10651. if (canvas) {
  10652. canvas.requestPointerLock();
  10653. }
  10654. };
  10655. this._onVRDisplayPointerUnrestricted = function () {
  10656. document.exitPointerLock();
  10657. };
  10658. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10659. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10660. }
  10661. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10662. Engine.audioEngine = new BABYLON.AudioEngine();
  10663. }
  10664. // Prepare buffer pointers
  10665. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10666. this._currentBufferPointers[i] = new BufferPointer();
  10667. }
  10668. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10669. // Load WebVR Devices
  10670. if (options.autoEnableWebVR) {
  10671. this.initWebVR();
  10672. }
  10673. // Detect if we are running on a faulty buggy OS.
  10674. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10675. // Detect if we are running on a faulty buggy desktop OS.
  10676. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10677. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10678. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10679. }
  10680. Object.defineProperty(Engine, "LastCreatedEngine", {
  10681. get: function () {
  10682. if (Engine.Instances.length === 0) {
  10683. return null;
  10684. }
  10685. return Engine.Instances[Engine.Instances.length - 1];
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "LastCreatedScene", {
  10691. get: function () {
  10692. var lastCreatedEngine = Engine.LastCreatedEngine;
  10693. if (!lastCreatedEngine) {
  10694. return null;
  10695. }
  10696. if (lastCreatedEngine.scenes.length === 0) {
  10697. return null;
  10698. }
  10699. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. /**
  10705. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10706. */
  10707. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10708. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10709. var engine = Engine.Instances[engineIndex];
  10710. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10711. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10712. }
  10713. }
  10714. };
  10715. Object.defineProperty(Engine, "NEVER", {
  10716. get: function () {
  10717. return Engine._NEVER;
  10718. },
  10719. enumerable: true,
  10720. configurable: true
  10721. });
  10722. Object.defineProperty(Engine, "ALWAYS", {
  10723. get: function () {
  10724. return Engine._ALWAYS;
  10725. },
  10726. enumerable: true,
  10727. configurable: true
  10728. });
  10729. Object.defineProperty(Engine, "LESS", {
  10730. get: function () {
  10731. return Engine._LESS;
  10732. },
  10733. enumerable: true,
  10734. configurable: true
  10735. });
  10736. Object.defineProperty(Engine, "EQUAL", {
  10737. get: function () {
  10738. return Engine._EQUAL;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(Engine, "LEQUAL", {
  10744. get: function () {
  10745. return Engine._LEQUAL;
  10746. },
  10747. enumerable: true,
  10748. configurable: true
  10749. });
  10750. Object.defineProperty(Engine, "GREATER", {
  10751. get: function () {
  10752. return Engine._GREATER;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(Engine, "GEQUAL", {
  10758. get: function () {
  10759. return Engine._GEQUAL;
  10760. },
  10761. enumerable: true,
  10762. configurable: true
  10763. });
  10764. Object.defineProperty(Engine, "NOTEQUAL", {
  10765. get: function () {
  10766. return Engine._NOTEQUAL;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(Engine, "KEEP", {
  10772. get: function () {
  10773. return Engine._KEEP;
  10774. },
  10775. enumerable: true,
  10776. configurable: true
  10777. });
  10778. Object.defineProperty(Engine, "REPLACE", {
  10779. get: function () {
  10780. return Engine._REPLACE;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(Engine, "INCR", {
  10786. get: function () {
  10787. return Engine._INCR;
  10788. },
  10789. enumerable: true,
  10790. configurable: true
  10791. });
  10792. Object.defineProperty(Engine, "DECR", {
  10793. get: function () {
  10794. return Engine._DECR;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(Engine, "INVERT", {
  10800. get: function () {
  10801. return Engine._INVERT;
  10802. },
  10803. enumerable: true,
  10804. configurable: true
  10805. });
  10806. Object.defineProperty(Engine, "INCR_WRAP", {
  10807. get: function () {
  10808. return Engine._INCR_WRAP;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "DECR_WRAP", {
  10814. get: function () {
  10815. return Engine._DECR_WRAP;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10821. get: function () {
  10822. return Engine._ALPHA_DISABLE;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10828. get: function () {
  10829. return Engine._ALPHA_ONEONE;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(Engine, "ALPHA_ADD", {
  10835. get: function () {
  10836. return Engine._ALPHA_ADD;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10842. get: function () {
  10843. return Engine._ALPHA_COMBINE;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10849. get: function () {
  10850. return Engine._ALPHA_SUBTRACT;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10856. get: function () {
  10857. return Engine._ALPHA_MULTIPLY;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10863. get: function () {
  10864. return Engine._ALPHA_MAXIMIZED;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10870. get: function () {
  10871. return Engine._ALPHA_PREMULTIPLIED;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10877. get: function () {
  10878. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10884. get: function () {
  10885. return Engine._ALPHA_INTERPOLATE;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10891. get: function () {
  10892. return Engine._ALPHA_SCREENMODE;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10898. get: function () {
  10899. return Engine._DELAYLOADSTATE_NONE;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10905. get: function () {
  10906. return Engine._DELAYLOADSTATE_LOADED;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10912. get: function () {
  10913. return Engine._DELAYLOADSTATE_LOADING;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10919. get: function () {
  10920. return Engine._DELAYLOADSTATE_NOTLOADED;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10926. get: function () {
  10927. return Engine._TEXTUREFORMAT_ALPHA;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10933. get: function () {
  10934. return Engine._TEXTUREFORMAT_LUMINANCE;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10940. /**
  10941. * R32F
  10942. */
  10943. get: function () {
  10944. return Engine._TEXTUREFORMAT_R32F;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10950. /**
  10951. * RG32F
  10952. */
  10953. get: function () {
  10954. return Engine._TEXTUREFORMAT_RG32F;
  10955. },
  10956. enumerable: true,
  10957. configurable: true
  10958. });
  10959. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10960. /**
  10961. * RGB32F
  10962. */
  10963. get: function () {
  10964. return Engine._TEXTUREFORMAT_RGB32F;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10970. /**
  10971. * RGBA32F
  10972. */
  10973. get: function () {
  10974. return Engine._TEXTUREFORMAT_RGBA32F;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10980. get: function () {
  10981. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10987. get: function () {
  10988. return Engine._TEXTUREFORMAT_RGB;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10994. get: function () {
  10995. return Engine._TEXTUREFORMAT_RGBA;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11001. get: function () {
  11002. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11008. get: function () {
  11009. return Engine._TEXTURETYPE_FLOAT;
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11015. get: function () {
  11016. return Engine._TEXTURETYPE_HALF_FLOAT;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11022. get: function () {
  11023. return Engine._SCALEMODE_FLOOR;
  11024. },
  11025. enumerable: true,
  11026. configurable: true
  11027. });
  11028. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11029. get: function () {
  11030. return Engine._SCALEMODE_NEAREST;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11036. get: function () {
  11037. return Engine._SCALEMODE_CEILING;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Engine, "Version", {
  11043. get: function () {
  11044. return "3.2.0-alphaB";
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11050. get: function () {
  11051. return this._vrExclusivePointerMode;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11057. get: function () {
  11058. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11064. get: function () {
  11065. return this._webGLVersion < 2 || this.forcePOTTextures;
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. Object.defineProperty(Engine.prototype, "badOS", {
  11071. get: function () {
  11072. return this._badOS;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11078. get: function () {
  11079. return this._badDesktopOS;
  11080. },
  11081. enumerable: true,
  11082. configurable: true
  11083. });
  11084. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11085. get: function () {
  11086. return this._performanceMonitor;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11092. get: function () {
  11093. return this._texturesSupported;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11099. get: function () {
  11100. return this._textureFormatInUse;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine.prototype, "currentViewport", {
  11106. get: function () {
  11107. return this._cachedViewport;
  11108. },
  11109. enumerable: true,
  11110. configurable: true
  11111. });
  11112. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11113. // Empty texture
  11114. get: function () {
  11115. if (!this._emptyTexture) {
  11116. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11117. }
  11118. return this._emptyTexture;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11124. get: function () {
  11125. if (!this._emptyTexture3D) {
  11126. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11127. }
  11128. return this._emptyTexture3D;
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11134. get: function () {
  11135. if (!this._emptyCubeTexture) {
  11136. var faceData = new Uint8Array(4);
  11137. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11138. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11139. }
  11140. return this._emptyCubeTexture;
  11141. },
  11142. enumerable: true,
  11143. configurable: true
  11144. });
  11145. Engine.prototype._rebuildInternalTextures = function () {
  11146. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11147. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11148. var internalTexture = currentState_1[_i];
  11149. internalTexture._rebuild();
  11150. }
  11151. };
  11152. Engine.prototype._rebuildEffects = function () {
  11153. for (var key in this._compiledEffects) {
  11154. var effect = this._compiledEffects[key];
  11155. effect._prepareEffect();
  11156. }
  11157. BABYLON.Effect.ResetCache();
  11158. };
  11159. Engine.prototype._rebuildBuffers = function () {
  11160. // Index / Vertex
  11161. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11162. var scene = _a[_i];
  11163. scene.resetCachedMaterial();
  11164. scene._rebuildGeometries();
  11165. scene._rebuildTextures();
  11166. }
  11167. // Uniforms
  11168. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11169. var uniformBuffer = _c[_b];
  11170. uniformBuffer._rebuild();
  11171. }
  11172. };
  11173. Engine.prototype._initGLContext = function () {
  11174. // Caps
  11175. this._caps = new EngineCapabilities();
  11176. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11177. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11178. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11179. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11180. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11181. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11182. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11183. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11184. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11185. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11186. // Infos
  11187. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11188. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11189. if (rendererInfo != null) {
  11190. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11191. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11192. }
  11193. if (!this._glVendor) {
  11194. this._glVendor = "Unknown vendor";
  11195. }
  11196. if (!this._glRenderer) {
  11197. this._glRenderer = "Unknown renderer";
  11198. }
  11199. // Constants
  11200. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11201. if (this._gl.RGBA16F !== 0x881A) {
  11202. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11203. }
  11204. if (this._gl.RGBA32F !== 0x8814) {
  11205. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11206. }
  11207. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11208. this._gl.DEPTH24_STENCIL8 = 35056;
  11209. }
  11210. // Extensions
  11211. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11212. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11213. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11214. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11215. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11216. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11217. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11218. 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');
  11219. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11220. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11221. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11222. this._caps.highPrecisionShaderSupported = true;
  11223. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11224. if (this._caps.timerQuery) {
  11225. if (this._webGLVersion === 1) {
  11226. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11227. }
  11228. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11229. }
  11230. // Checks if some of the format renders first to allow the use of webgl inspector.
  11231. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11232. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11233. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11234. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11235. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11236. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11237. if (this._webGLVersion > 1) {
  11238. this._gl.HALF_FLOAT_OES = 0x140B;
  11239. }
  11240. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11241. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11242. // Draw buffers
  11243. if (this._webGLVersion > 1) {
  11244. this._caps.drawBuffersExtension = true;
  11245. }
  11246. else {
  11247. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11248. if (drawBuffersExtension !== null) {
  11249. this._caps.drawBuffersExtension = true;
  11250. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11251. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11252. for (var i = 0; i < 16; i++) {
  11253. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11254. }
  11255. }
  11256. else {
  11257. this._caps.drawBuffersExtension = false;
  11258. }
  11259. }
  11260. // Depth Texture
  11261. if (this._webGLVersion > 1) {
  11262. this._caps.depthTextureExtension = true;
  11263. }
  11264. else {
  11265. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11266. if (depthTextureExtension != null) {
  11267. this._caps.depthTextureExtension = true;
  11268. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11269. }
  11270. }
  11271. // Vertex array object
  11272. if (this._webGLVersion > 1) {
  11273. this._caps.vertexArrayObject = true;
  11274. }
  11275. else {
  11276. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11277. if (vertexArrayObjectExtension != null) {
  11278. this._caps.vertexArrayObject = true;
  11279. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11280. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11281. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11282. }
  11283. else {
  11284. this._caps.vertexArrayObject = false;
  11285. }
  11286. }
  11287. // Instances count
  11288. if (this._webGLVersion > 1) {
  11289. this._caps.instancedArrays = true;
  11290. }
  11291. else {
  11292. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11293. if (instanceExtension != null) {
  11294. this._caps.instancedArrays = true;
  11295. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11296. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11297. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11298. }
  11299. else {
  11300. this._caps.instancedArrays = false;
  11301. }
  11302. }
  11303. // Intelligently add supported compressed formats in order to check for.
  11304. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11305. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11306. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11307. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11308. if (this._caps.astc)
  11309. this.texturesSupported.push('-astc.ktx');
  11310. if (this._caps.s3tc)
  11311. this.texturesSupported.push('-dxt.ktx');
  11312. if (this._caps.pvrtc)
  11313. this.texturesSupported.push('-pvrtc.ktx');
  11314. if (this._caps.etc2)
  11315. this.texturesSupported.push('-etc2.ktx');
  11316. if (this._caps.etc1)
  11317. this.texturesSupported.push('-etc1.ktx');
  11318. if (this._gl.getShaderPrecisionFormat) {
  11319. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11320. if (highp) {
  11321. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11322. }
  11323. }
  11324. // Depth buffer
  11325. this.setDepthBuffer(true);
  11326. this.setDepthFunctionToLessOrEqual();
  11327. this.setDepthWrite(true);
  11328. // Texture maps
  11329. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11330. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11331. this._nextFreeTextureSlots.push(slot);
  11332. }
  11333. };
  11334. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11335. get: function () {
  11336. return this._webGLVersion;
  11337. },
  11338. enumerable: true,
  11339. configurable: true
  11340. });
  11341. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11342. /**
  11343. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11344. */
  11345. get: function () {
  11346. return this._isStencilEnable;
  11347. },
  11348. enumerable: true,
  11349. configurable: true
  11350. });
  11351. Engine.prototype._prepareWorkingCanvas = function () {
  11352. if (this._workingCanvas) {
  11353. return;
  11354. }
  11355. this._workingCanvas = document.createElement("canvas");
  11356. var context = this._workingCanvas.getContext("2d");
  11357. if (context) {
  11358. this._workingContext = context;
  11359. }
  11360. };
  11361. Engine.prototype.resetTextureCache = function () {
  11362. for (var key in this._boundTexturesCache) {
  11363. var boundTexture = this._boundTexturesCache[key];
  11364. if (boundTexture) {
  11365. this._removeDesignatedSlot(boundTexture);
  11366. }
  11367. this._boundTexturesCache[key] = null;
  11368. }
  11369. if (!this.disableTextureBindingOptimization) {
  11370. this._nextFreeTextureSlots = [];
  11371. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11372. this._nextFreeTextureSlots.push(slot);
  11373. }
  11374. }
  11375. this._currentTextureChannel = -1;
  11376. };
  11377. Engine.prototype.isDeterministicLockStep = function () {
  11378. return this._deterministicLockstep;
  11379. };
  11380. Engine.prototype.getLockstepMaxSteps = function () {
  11381. return this._lockstepMaxSteps;
  11382. };
  11383. Engine.prototype.getGlInfo = function () {
  11384. return {
  11385. vendor: this._glVendor,
  11386. renderer: this._glRenderer,
  11387. version: this._glVersion
  11388. };
  11389. };
  11390. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11391. if (useScreen === void 0) { useScreen = false; }
  11392. var viewport = camera.viewport;
  11393. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11394. };
  11395. Engine.prototype.getRenderWidth = function (useScreen) {
  11396. if (useScreen === void 0) { useScreen = false; }
  11397. if (!useScreen && this._currentRenderTarget) {
  11398. return this._currentRenderTarget.width;
  11399. }
  11400. return this._gl.drawingBufferWidth;
  11401. };
  11402. Engine.prototype.getRenderHeight = function (useScreen) {
  11403. if (useScreen === void 0) { useScreen = false; }
  11404. if (!useScreen && this._currentRenderTarget) {
  11405. return this._currentRenderTarget.height;
  11406. }
  11407. return this._gl.drawingBufferHeight;
  11408. };
  11409. Engine.prototype.getRenderingCanvas = function () {
  11410. return this._renderingCanvas;
  11411. };
  11412. Engine.prototype.getRenderingCanvasClientRect = function () {
  11413. if (!this._renderingCanvas) {
  11414. return null;
  11415. }
  11416. return this._renderingCanvas.getBoundingClientRect();
  11417. };
  11418. Engine.prototype.setHardwareScalingLevel = function (level) {
  11419. this._hardwareScalingLevel = level;
  11420. this.resize();
  11421. };
  11422. Engine.prototype.getHardwareScalingLevel = function () {
  11423. return this._hardwareScalingLevel;
  11424. };
  11425. Engine.prototype.getLoadedTexturesCache = function () {
  11426. return this._internalTexturesCache;
  11427. };
  11428. Engine.prototype.getCaps = function () {
  11429. return this._caps;
  11430. };
  11431. Object.defineProperty(Engine.prototype, "drawCalls", {
  11432. /** The number of draw calls submitted last frame */
  11433. get: function () {
  11434. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11435. return 0;
  11436. },
  11437. enumerable: true,
  11438. configurable: true
  11439. });
  11440. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11441. get: function () {
  11442. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11443. return null;
  11444. },
  11445. enumerable: true,
  11446. configurable: true
  11447. });
  11448. Engine.prototype.getDepthFunction = function () {
  11449. return this._depthCullingState.depthFunc;
  11450. };
  11451. Engine.prototype.setDepthFunction = function (depthFunc) {
  11452. this._depthCullingState.depthFunc = depthFunc;
  11453. };
  11454. Engine.prototype.setDepthFunctionToGreater = function () {
  11455. this._depthCullingState.depthFunc = this._gl.GREATER;
  11456. };
  11457. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11458. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11459. };
  11460. Engine.prototype.setDepthFunctionToLess = function () {
  11461. this._depthCullingState.depthFunc = this._gl.LESS;
  11462. };
  11463. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11464. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11465. };
  11466. Engine.prototype.getStencilBuffer = function () {
  11467. return this._stencilState.stencilTest;
  11468. };
  11469. Engine.prototype.setStencilBuffer = function (enable) {
  11470. this._stencilState.stencilTest = enable;
  11471. };
  11472. Engine.prototype.getStencilMask = function () {
  11473. return this._stencilState.stencilMask;
  11474. };
  11475. Engine.prototype.setStencilMask = function (mask) {
  11476. this._stencilState.stencilMask = mask;
  11477. };
  11478. Engine.prototype.getStencilFunction = function () {
  11479. return this._stencilState.stencilFunc;
  11480. };
  11481. Engine.prototype.getStencilFunctionReference = function () {
  11482. return this._stencilState.stencilFuncRef;
  11483. };
  11484. Engine.prototype.getStencilFunctionMask = function () {
  11485. return this._stencilState.stencilFuncMask;
  11486. };
  11487. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11488. this._stencilState.stencilFunc = stencilFunc;
  11489. };
  11490. Engine.prototype.setStencilFunctionReference = function (reference) {
  11491. this._stencilState.stencilFuncRef = reference;
  11492. };
  11493. Engine.prototype.setStencilFunctionMask = function (mask) {
  11494. this._stencilState.stencilFuncMask = mask;
  11495. };
  11496. Engine.prototype.getStencilOperationFail = function () {
  11497. return this._stencilState.stencilOpStencilFail;
  11498. };
  11499. Engine.prototype.getStencilOperationDepthFail = function () {
  11500. return this._stencilState.stencilOpDepthFail;
  11501. };
  11502. Engine.prototype.getStencilOperationPass = function () {
  11503. return this._stencilState.stencilOpStencilDepthPass;
  11504. };
  11505. Engine.prototype.setStencilOperationFail = function (operation) {
  11506. this._stencilState.stencilOpStencilFail = operation;
  11507. };
  11508. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11509. this._stencilState.stencilOpDepthFail = operation;
  11510. };
  11511. Engine.prototype.setStencilOperationPass = function (operation) {
  11512. this._stencilState.stencilOpStencilDepthPass = operation;
  11513. };
  11514. Engine.prototype.setDitheringState = function (value) {
  11515. if (value) {
  11516. this._gl.enable(this._gl.DITHER);
  11517. }
  11518. else {
  11519. this._gl.disable(this._gl.DITHER);
  11520. }
  11521. };
  11522. Engine.prototype.setRasterizerState = function (value) {
  11523. if (value) {
  11524. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11525. }
  11526. else {
  11527. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11528. }
  11529. };
  11530. /**
  11531. * stop executing a render loop function and remove it from the execution array
  11532. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11533. */
  11534. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11535. if (!renderFunction) {
  11536. this._activeRenderLoops = [];
  11537. return;
  11538. }
  11539. var index = this._activeRenderLoops.indexOf(renderFunction);
  11540. if (index >= 0) {
  11541. this._activeRenderLoops.splice(index, 1);
  11542. }
  11543. };
  11544. Engine.prototype._renderLoop = function () {
  11545. if (!this._contextWasLost) {
  11546. var shouldRender = true;
  11547. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11548. shouldRender = false;
  11549. }
  11550. if (shouldRender) {
  11551. // Start new frame
  11552. this.beginFrame();
  11553. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11554. var renderFunction = this._activeRenderLoops[index];
  11555. renderFunction();
  11556. }
  11557. // Present
  11558. this.endFrame();
  11559. }
  11560. }
  11561. if (this._activeRenderLoops.length > 0) {
  11562. // Register new frame
  11563. var requester = null;
  11564. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11565. requester = this._vrDisplay;
  11566. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11567. }
  11568. else {
  11569. this._renderingQueueLaunched = false;
  11570. }
  11571. };
  11572. /**
  11573. * Register and execute a render loop. The engine can have more than one render function.
  11574. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11575. * @example
  11576. * engine.runRenderLoop(function () {
  11577. * scene.render()
  11578. * })
  11579. */
  11580. Engine.prototype.runRenderLoop = function (renderFunction) {
  11581. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11582. return;
  11583. }
  11584. this._activeRenderLoops.push(renderFunction);
  11585. if (!this._renderingQueueLaunched) {
  11586. this._renderingQueueLaunched = true;
  11587. this._bindedRenderFunction = this._renderLoop.bind(this);
  11588. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11589. }
  11590. };
  11591. /**
  11592. * Toggle full screen mode.
  11593. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11594. * @param {any} options - an options object to be sent to the requestFullscreen function
  11595. */
  11596. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11597. if (this.isFullscreen) {
  11598. BABYLON.Tools.ExitFullscreen();
  11599. }
  11600. else {
  11601. this._pointerLockRequested = requestPointerLock;
  11602. if (this._renderingCanvas) {
  11603. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11604. }
  11605. }
  11606. };
  11607. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11608. if (stencil === void 0) { stencil = false; }
  11609. this.applyStates();
  11610. var mode = 0;
  11611. if (backBuffer && color) {
  11612. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11613. mode |= this._gl.COLOR_BUFFER_BIT;
  11614. }
  11615. if (depth) {
  11616. this._gl.clearDepth(1.0);
  11617. mode |= this._gl.DEPTH_BUFFER_BIT;
  11618. }
  11619. if (stencil) {
  11620. this._gl.clearStencil(0);
  11621. mode |= this._gl.STENCIL_BUFFER_BIT;
  11622. }
  11623. this._gl.clear(mode);
  11624. };
  11625. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11626. var gl = this._gl;
  11627. // Save state
  11628. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11629. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11630. // Change state
  11631. gl.enable(gl.SCISSOR_TEST);
  11632. gl.scissor(x, y, width, height);
  11633. // Clear
  11634. this.clear(clearColor, true, true, true);
  11635. // Restore state
  11636. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11637. if (curScissor === true) {
  11638. gl.enable(gl.SCISSOR_TEST);
  11639. }
  11640. else {
  11641. gl.disable(gl.SCISSOR_TEST);
  11642. }
  11643. };
  11644. /**
  11645. * Set the WebGL's viewport
  11646. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11647. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11648. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11649. */
  11650. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11651. var width = requiredWidth || this.getRenderWidth();
  11652. var height = requiredHeight || this.getRenderHeight();
  11653. var x = viewport.x || 0;
  11654. var y = viewport.y || 0;
  11655. this._cachedViewport = viewport;
  11656. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11657. };
  11658. /**
  11659. * Directly set the WebGL Viewport
  11660. * The x, y, width & height are directly passed to the WebGL call
  11661. * @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.
  11662. */
  11663. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11664. var currentViewport = this._cachedViewport;
  11665. this._cachedViewport = null;
  11666. this._gl.viewport(x, y, width, height);
  11667. return currentViewport;
  11668. };
  11669. Engine.prototype.beginFrame = function () {
  11670. this.onBeginFrameObservable.notifyObservers(this);
  11671. this._measureFps();
  11672. };
  11673. Engine.prototype.endFrame = function () {
  11674. //force a flush in case we are using a bad OS.
  11675. if (this._badOS) {
  11676. this.flushFramebuffer();
  11677. }
  11678. //submit frame to the vr device, if enabled
  11679. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11680. // TODO: We should only submit the frame if we read frameData successfully.
  11681. this._vrDisplay.submitFrame();
  11682. }
  11683. this.onEndFrameObservable.notifyObservers(this);
  11684. };
  11685. /**
  11686. * resize the view according to the canvas' size.
  11687. * @example
  11688. * window.addEventListener("resize", function () {
  11689. * engine.resize();
  11690. * });
  11691. */
  11692. Engine.prototype.resize = function () {
  11693. // We're not resizing the size of the canvas while in VR mode & presenting
  11694. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11695. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11696. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11697. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11698. }
  11699. };
  11700. /**
  11701. * force a specific size of the canvas
  11702. * @param {number} width - the new canvas' width
  11703. * @param {number} height - the new canvas' height
  11704. */
  11705. Engine.prototype.setSize = function (width, height) {
  11706. if (!this._renderingCanvas) {
  11707. return;
  11708. }
  11709. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11710. return;
  11711. }
  11712. this._renderingCanvas.width = width;
  11713. this._renderingCanvas.height = height;
  11714. for (var index = 0; index < this.scenes.length; index++) {
  11715. var scene = this.scenes[index];
  11716. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11717. var cam = scene.cameras[camIndex];
  11718. cam._currentRenderId = 0;
  11719. }
  11720. }
  11721. if (this.onResizeObservable.hasObservers) {
  11722. this.onResizeObservable.notifyObservers(this);
  11723. }
  11724. };
  11725. // WebVR functions
  11726. Engine.prototype.isVRDevicePresent = function () {
  11727. return !!this._vrDisplay;
  11728. };
  11729. Engine.prototype.getVRDevice = function () {
  11730. return this._vrDisplay;
  11731. };
  11732. /**
  11733. * Initializes a webVR display and starts listening to display change events.
  11734. * The onVRDisplayChangedObservable will be notified upon these changes.
  11735. * @returns The onVRDisplayChangedObservable.
  11736. */
  11737. Engine.prototype.initWebVR = function () {
  11738. this.initWebVRAsync();
  11739. return this.onVRDisplayChangedObservable;
  11740. };
  11741. /**
  11742. * Initializes a webVR display and starts listening to display change events.
  11743. * The onVRDisplayChangedObservable will be notified upon these changes.
  11744. * @returns A promise containing a VRDisplay and if vr is supported.
  11745. */
  11746. Engine.prototype.initWebVRAsync = function () {
  11747. var _this = this;
  11748. var notifyObservers = function () {
  11749. var eventArgs = {
  11750. vrDisplay: _this._vrDisplay,
  11751. vrSupported: _this._vrSupported
  11752. };
  11753. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11754. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11755. };
  11756. if (!this._onVrDisplayConnect) {
  11757. this._onVrDisplayConnect = function (event) {
  11758. _this._vrDisplay = event.display;
  11759. notifyObservers();
  11760. };
  11761. this._onVrDisplayDisconnect = function () {
  11762. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11763. _this._vrDisplay = undefined;
  11764. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11765. notifyObservers();
  11766. };
  11767. this._onVrDisplayPresentChange = function () {
  11768. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11769. };
  11770. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11771. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11772. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11773. }
  11774. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11775. this._webVRInitPromise.then(notifyObservers);
  11776. return this._webVRInitPromise;
  11777. };
  11778. Engine.prototype.enableVR = function () {
  11779. var _this = this;
  11780. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11781. var onResolved = function () {
  11782. _this.onVRRequestPresentComplete.notifyObservers(true);
  11783. _this._onVRFullScreenTriggered();
  11784. };
  11785. var onRejected = function () {
  11786. _this.onVRRequestPresentComplete.notifyObservers(false);
  11787. };
  11788. this.onVRRequestPresentStart.notifyObservers(this);
  11789. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11790. }
  11791. };
  11792. Engine.prototype.disableVR = function () {
  11793. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11794. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11795. }
  11796. };
  11797. Engine.prototype._getVRDisplaysAsync = function () {
  11798. var _this = this;
  11799. return new Promise(function (res, rej) {
  11800. if (navigator.getVRDisplays) {
  11801. navigator.getVRDisplays().then(function (devices) {
  11802. _this._vrSupported = true;
  11803. // note that devices may actually be an empty array. This is fine;
  11804. // we expect this._vrDisplay to be undefined in this case.
  11805. _this._vrDisplay = devices[0];
  11806. res({
  11807. vrDisplay: _this._vrDisplay,
  11808. vrSupported: _this._vrSupported
  11809. });
  11810. });
  11811. }
  11812. else {
  11813. _this._vrDisplay = undefined;
  11814. _this._vrSupported = false;
  11815. res({
  11816. vrDisplay: _this._vrDisplay,
  11817. vrSupported: _this._vrSupported
  11818. });
  11819. }
  11820. });
  11821. };
  11822. /**
  11823. * Binds the frame buffer to the specified texture.
  11824. * @param texture The texture to render to or null for the default canvas
  11825. * @param faceIndex The face of the texture to render to in case of cube texture
  11826. * @param requiredWidth The width of the target to render to
  11827. * @param requiredHeight The height of the target to render to
  11828. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11829. * @param depthStencilTexture The depth stencil texture to use to render
  11830. */
  11831. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11832. if (this._currentRenderTarget) {
  11833. this.unBindFramebuffer(this._currentRenderTarget);
  11834. }
  11835. this._currentRenderTarget = texture;
  11836. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11837. var gl = this._gl;
  11838. if (texture.isCube) {
  11839. if (faceIndex === undefined) {
  11840. faceIndex = 0;
  11841. }
  11842. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11843. if (depthStencilTexture) {
  11844. if (depthStencilTexture._generateStencilBuffer) {
  11845. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11846. }
  11847. else {
  11848. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11849. }
  11850. }
  11851. }
  11852. if (this._cachedViewport && !forceFullscreenViewport) {
  11853. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11854. }
  11855. else {
  11856. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11857. }
  11858. this.wipeCaches();
  11859. };
  11860. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11861. if (this._currentFramebuffer !== framebuffer) {
  11862. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11863. this._currentFramebuffer = framebuffer;
  11864. }
  11865. };
  11866. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11867. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11868. this._currentRenderTarget = null;
  11869. // If MSAA, we need to bitblt back to main texture
  11870. var gl = this._gl;
  11871. if (texture._MSAAFramebuffer) {
  11872. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11873. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11874. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11875. }
  11876. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11877. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11878. gl.generateMipmap(gl.TEXTURE_2D);
  11879. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11880. }
  11881. if (onBeforeUnbind) {
  11882. if (texture._MSAAFramebuffer) {
  11883. // Bind the correct framebuffer
  11884. this.bindUnboundFramebuffer(texture._framebuffer);
  11885. }
  11886. onBeforeUnbind();
  11887. }
  11888. this.bindUnboundFramebuffer(null);
  11889. };
  11890. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11891. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11892. this._currentRenderTarget = null;
  11893. // If MSAA, we need to bitblt back to main texture
  11894. var gl = this._gl;
  11895. if (textures[0]._MSAAFramebuffer) {
  11896. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11897. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11898. var attachments = textures[0]._attachments;
  11899. if (!attachments) {
  11900. attachments = new Array(textures.length);
  11901. textures[0]._attachments = attachments;
  11902. }
  11903. for (var i = 0; i < textures.length; i++) {
  11904. var texture = textures[i];
  11905. for (var j = 0; j < attachments.length; j++) {
  11906. attachments[j] = gl.NONE;
  11907. }
  11908. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11909. gl.readBuffer(attachments[i]);
  11910. gl.drawBuffers(attachments);
  11911. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11912. }
  11913. for (var i = 0; i < attachments.length; i++) {
  11914. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11915. }
  11916. gl.drawBuffers(attachments);
  11917. }
  11918. for (var i = 0; i < textures.length; i++) {
  11919. var texture = textures[i];
  11920. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11921. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11922. gl.generateMipmap(gl.TEXTURE_2D);
  11923. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11924. }
  11925. }
  11926. if (onBeforeUnbind) {
  11927. if (textures[0]._MSAAFramebuffer) {
  11928. // Bind the correct framebuffer
  11929. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11930. }
  11931. onBeforeUnbind();
  11932. }
  11933. this.bindUnboundFramebuffer(null);
  11934. };
  11935. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11936. if (texture.generateMipMaps) {
  11937. var gl = this._gl;
  11938. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11939. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11940. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11941. }
  11942. };
  11943. Engine.prototype.flushFramebuffer = function () {
  11944. this._gl.flush();
  11945. };
  11946. Engine.prototype.restoreDefaultFramebuffer = function () {
  11947. if (this._currentRenderTarget) {
  11948. this.unBindFramebuffer(this._currentRenderTarget);
  11949. }
  11950. else {
  11951. this.bindUnboundFramebuffer(null);
  11952. }
  11953. if (this._cachedViewport) {
  11954. this.setViewport(this._cachedViewport);
  11955. }
  11956. this.wipeCaches();
  11957. };
  11958. // UBOs
  11959. Engine.prototype.createUniformBuffer = function (elements) {
  11960. var ubo = this._gl.createBuffer();
  11961. if (!ubo) {
  11962. throw new Error("Unable to create uniform buffer");
  11963. }
  11964. this.bindUniformBuffer(ubo);
  11965. if (elements instanceof Float32Array) {
  11966. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11967. }
  11968. else {
  11969. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11970. }
  11971. this.bindUniformBuffer(null);
  11972. ubo.references = 1;
  11973. return ubo;
  11974. };
  11975. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11976. var ubo = this._gl.createBuffer();
  11977. if (!ubo) {
  11978. throw new Error("Unable to create dynamic uniform buffer");
  11979. }
  11980. this.bindUniformBuffer(ubo);
  11981. if (elements instanceof Float32Array) {
  11982. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11983. }
  11984. else {
  11985. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11986. }
  11987. this.bindUniformBuffer(null);
  11988. ubo.references = 1;
  11989. return ubo;
  11990. };
  11991. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11992. this.bindUniformBuffer(uniformBuffer);
  11993. if (offset === undefined) {
  11994. offset = 0;
  11995. }
  11996. if (count === undefined) {
  11997. if (elements instanceof Float32Array) {
  11998. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11999. }
  12000. else {
  12001. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12002. }
  12003. }
  12004. else {
  12005. if (elements instanceof Float32Array) {
  12006. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12007. }
  12008. else {
  12009. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12010. }
  12011. }
  12012. this.bindUniformBuffer(null);
  12013. };
  12014. // VBOs
  12015. Engine.prototype._resetVertexBufferBinding = function () {
  12016. this.bindArrayBuffer(null);
  12017. this._cachedVertexBuffers = null;
  12018. };
  12019. Engine.prototype.createVertexBuffer = function (vertices) {
  12020. var vbo = this._gl.createBuffer();
  12021. if (!vbo) {
  12022. throw new Error("Unable to create vertex buffer");
  12023. }
  12024. this.bindArrayBuffer(vbo);
  12025. if (vertices instanceof Float32Array) {
  12026. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12027. }
  12028. else {
  12029. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12030. }
  12031. this._resetVertexBufferBinding();
  12032. vbo.references = 1;
  12033. return vbo;
  12034. };
  12035. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12036. var vbo = this._gl.createBuffer();
  12037. if (!vbo) {
  12038. throw new Error("Unable to create dynamic vertex buffer");
  12039. }
  12040. this.bindArrayBuffer(vbo);
  12041. if (vertices instanceof Float32Array) {
  12042. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12043. }
  12044. else {
  12045. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12046. }
  12047. this._resetVertexBufferBinding();
  12048. vbo.references = 1;
  12049. return vbo;
  12050. };
  12051. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12052. if (offset === void 0) { offset = 0; }
  12053. // Force cache update
  12054. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12055. this.bindIndexBuffer(indexBuffer);
  12056. var arrayBuffer;
  12057. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12058. arrayBuffer = indices;
  12059. }
  12060. else {
  12061. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12062. }
  12063. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12064. this._resetIndexBufferBinding();
  12065. };
  12066. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12067. this.bindArrayBuffer(vertexBuffer);
  12068. if (offset === undefined) {
  12069. offset = 0;
  12070. }
  12071. if (count === undefined) {
  12072. if (vertices instanceof Float32Array) {
  12073. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12074. }
  12075. else {
  12076. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12077. }
  12078. }
  12079. else {
  12080. if (vertices instanceof Float32Array) {
  12081. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12082. }
  12083. else {
  12084. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12085. }
  12086. }
  12087. this._resetVertexBufferBinding();
  12088. };
  12089. Engine.prototype._resetIndexBufferBinding = function () {
  12090. this.bindIndexBuffer(null);
  12091. this._cachedIndexBuffer = null;
  12092. };
  12093. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12094. var vbo = this._gl.createBuffer();
  12095. if (!vbo) {
  12096. throw new Error("Unable to create index buffer");
  12097. }
  12098. this.bindIndexBuffer(vbo);
  12099. // Check for 32 bits indices
  12100. var arrayBuffer;
  12101. var need32Bits = false;
  12102. if (indices instanceof Uint16Array) {
  12103. arrayBuffer = indices;
  12104. }
  12105. else {
  12106. //check 32 bit support
  12107. if (this._caps.uintIndices) {
  12108. if (indices instanceof Uint32Array) {
  12109. arrayBuffer = indices;
  12110. need32Bits = true;
  12111. }
  12112. else {
  12113. //number[] or Int32Array, check if 32 bit is necessary
  12114. for (var index = 0; index < indices.length; index++) {
  12115. if (indices[index] > 65535) {
  12116. need32Bits = true;
  12117. break;
  12118. }
  12119. }
  12120. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12121. }
  12122. }
  12123. else {
  12124. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12125. arrayBuffer = new Uint16Array(indices);
  12126. }
  12127. }
  12128. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12129. this._resetIndexBufferBinding();
  12130. vbo.references = 1;
  12131. vbo.is32Bits = need32Bits;
  12132. return vbo;
  12133. };
  12134. Engine.prototype.bindArrayBuffer = function (buffer) {
  12135. if (!this._vaoRecordInProgress) {
  12136. this._unbindVertexArrayObject();
  12137. }
  12138. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12139. };
  12140. Engine.prototype.bindUniformBuffer = function (buffer) {
  12141. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12142. };
  12143. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12144. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12145. };
  12146. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12147. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12148. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12149. };
  12150. ;
  12151. Engine.prototype.bindIndexBuffer = function (buffer) {
  12152. if (!this._vaoRecordInProgress) {
  12153. this._unbindVertexArrayObject();
  12154. }
  12155. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12156. };
  12157. Engine.prototype.bindBuffer = function (buffer, target) {
  12158. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12159. this._gl.bindBuffer(target, buffer);
  12160. this._currentBoundBuffer[target] = buffer;
  12161. }
  12162. };
  12163. Engine.prototype.updateArrayBuffer = function (data) {
  12164. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12165. };
  12166. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12167. var pointer = this._currentBufferPointers[indx];
  12168. var changed = false;
  12169. if (!pointer.active) {
  12170. changed = true;
  12171. pointer.active = true;
  12172. pointer.index = indx;
  12173. pointer.size = size;
  12174. pointer.type = type;
  12175. pointer.normalized = normalized;
  12176. pointer.stride = stride;
  12177. pointer.offset = offset;
  12178. pointer.buffer = buffer;
  12179. }
  12180. else {
  12181. if (pointer.buffer !== buffer) {
  12182. pointer.buffer = buffer;
  12183. changed = true;
  12184. }
  12185. if (pointer.size !== size) {
  12186. pointer.size = size;
  12187. changed = true;
  12188. }
  12189. if (pointer.type !== type) {
  12190. pointer.type = type;
  12191. changed = true;
  12192. }
  12193. if (pointer.normalized !== normalized) {
  12194. pointer.normalized = normalized;
  12195. changed = true;
  12196. }
  12197. if (pointer.stride !== stride) {
  12198. pointer.stride = stride;
  12199. changed = true;
  12200. }
  12201. if (pointer.offset !== offset) {
  12202. pointer.offset = offset;
  12203. changed = true;
  12204. }
  12205. }
  12206. if (changed || this._vaoRecordInProgress) {
  12207. this.bindArrayBuffer(buffer);
  12208. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12209. }
  12210. };
  12211. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12212. if (indexBuffer == null) {
  12213. return;
  12214. }
  12215. if (this._cachedIndexBuffer !== indexBuffer) {
  12216. this._cachedIndexBuffer = indexBuffer;
  12217. this.bindIndexBuffer(indexBuffer);
  12218. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12219. }
  12220. };
  12221. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12222. var attributes = effect.getAttributesNames();
  12223. if (!this._vaoRecordInProgress) {
  12224. this._unbindVertexArrayObject();
  12225. }
  12226. this.unbindAllAttributes();
  12227. for (var index = 0; index < attributes.length; index++) {
  12228. var order = effect.getAttributeLocation(index);
  12229. if (order >= 0) {
  12230. var vertexBuffer = vertexBuffers[attributes[index]];
  12231. if (!vertexBuffer) {
  12232. continue;
  12233. }
  12234. this._gl.enableVertexAttribArray(order);
  12235. if (!this._vaoRecordInProgress) {
  12236. this._vertexAttribArraysEnabled[order] = true;
  12237. }
  12238. var buffer = vertexBuffer.getBuffer();
  12239. if (buffer) {
  12240. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12241. if (vertexBuffer.getIsInstanced()) {
  12242. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12243. if (!this._vaoRecordInProgress) {
  12244. this._currentInstanceLocations.push(order);
  12245. this._currentInstanceBuffers.push(buffer);
  12246. }
  12247. }
  12248. }
  12249. }
  12250. }
  12251. };
  12252. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12253. var vao = this._gl.createVertexArray();
  12254. this._vaoRecordInProgress = true;
  12255. this._gl.bindVertexArray(vao);
  12256. this._mustWipeVertexAttributes = true;
  12257. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12258. this.bindIndexBuffer(indexBuffer);
  12259. this._vaoRecordInProgress = false;
  12260. this._gl.bindVertexArray(null);
  12261. return vao;
  12262. };
  12263. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12264. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12265. this._cachedVertexArrayObject = vertexArrayObject;
  12266. this._gl.bindVertexArray(vertexArrayObject);
  12267. this._cachedVertexBuffers = null;
  12268. this._cachedIndexBuffer = null;
  12269. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12270. this._mustWipeVertexAttributes = true;
  12271. }
  12272. };
  12273. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12274. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12275. this._cachedVertexBuffers = vertexBuffer;
  12276. this._cachedEffectForVertexBuffers = effect;
  12277. var attributesCount = effect.getAttributesCount();
  12278. this._unbindVertexArrayObject();
  12279. this.unbindAllAttributes();
  12280. var offset = 0;
  12281. for (var index = 0; index < attributesCount; index++) {
  12282. if (index < vertexDeclaration.length) {
  12283. var order = effect.getAttributeLocation(index);
  12284. if (order >= 0) {
  12285. this._gl.enableVertexAttribArray(order);
  12286. this._vertexAttribArraysEnabled[order] = true;
  12287. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12288. }
  12289. offset += vertexDeclaration[index] * 4;
  12290. }
  12291. }
  12292. }
  12293. this._bindIndexBufferWithCache(indexBuffer);
  12294. };
  12295. Engine.prototype._unbindVertexArrayObject = function () {
  12296. if (!this._cachedVertexArrayObject) {
  12297. return;
  12298. }
  12299. this._cachedVertexArrayObject = null;
  12300. this._gl.bindVertexArray(null);
  12301. };
  12302. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12303. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12304. this._cachedVertexBuffers = vertexBuffers;
  12305. this._cachedEffectForVertexBuffers = effect;
  12306. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12307. }
  12308. this._bindIndexBufferWithCache(indexBuffer);
  12309. };
  12310. Engine.prototype.unbindInstanceAttributes = function () {
  12311. var boundBuffer;
  12312. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12313. var instancesBuffer = this._currentInstanceBuffers[i];
  12314. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12315. boundBuffer = instancesBuffer;
  12316. this.bindArrayBuffer(instancesBuffer);
  12317. }
  12318. var offsetLocation = this._currentInstanceLocations[i];
  12319. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12320. }
  12321. this._currentInstanceBuffers.length = 0;
  12322. this._currentInstanceLocations.length = 0;
  12323. };
  12324. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12325. this._gl.deleteVertexArray(vao);
  12326. };
  12327. Engine.prototype._releaseBuffer = function (buffer) {
  12328. buffer.references--;
  12329. if (buffer.references === 0) {
  12330. this._gl.deleteBuffer(buffer);
  12331. return true;
  12332. }
  12333. return false;
  12334. };
  12335. Engine.prototype.createInstancesBuffer = function (capacity) {
  12336. var buffer = this._gl.createBuffer();
  12337. if (!buffer) {
  12338. throw new Error("Unable to create instance buffer");
  12339. }
  12340. buffer.capacity = capacity;
  12341. this.bindArrayBuffer(buffer);
  12342. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12343. return buffer;
  12344. };
  12345. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12346. this._gl.deleteBuffer(buffer);
  12347. };
  12348. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12349. this.bindArrayBuffer(instancesBuffer);
  12350. if (data) {
  12351. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12352. }
  12353. if (offsetLocations[0].index !== undefined) {
  12354. var stride = 0;
  12355. for (var i = 0; i < offsetLocations.length; i++) {
  12356. var ai = offsetLocations[i];
  12357. stride += ai.attributeSize * 4;
  12358. }
  12359. for (var i = 0; i < offsetLocations.length; i++) {
  12360. var ai = offsetLocations[i];
  12361. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12362. this._gl.enableVertexAttribArray(ai.index);
  12363. this._vertexAttribArraysEnabled[ai.index] = true;
  12364. }
  12365. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12366. this._gl.vertexAttribDivisor(ai.index, 1);
  12367. this._currentInstanceLocations.push(ai.index);
  12368. this._currentInstanceBuffers.push(instancesBuffer);
  12369. }
  12370. }
  12371. else {
  12372. for (var index = 0; index < 4; index++) {
  12373. var offsetLocation = offsetLocations[index];
  12374. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12375. this._gl.enableVertexAttribArray(offsetLocation);
  12376. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12377. }
  12378. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12379. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12380. this._currentInstanceLocations.push(offsetLocation);
  12381. this._currentInstanceBuffers.push(instancesBuffer);
  12382. }
  12383. }
  12384. };
  12385. Engine.prototype.applyStates = function () {
  12386. this._depthCullingState.apply(this._gl);
  12387. this._stencilState.apply(this._gl);
  12388. this._alphaState.apply(this._gl);
  12389. };
  12390. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12391. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12392. };
  12393. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12394. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12395. };
  12396. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12397. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12398. };
  12399. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12400. // Apply states
  12401. this.applyStates();
  12402. this._drawCalls.addCount(1, false);
  12403. // Render
  12404. var drawMode = this.DrawMode(fillMode);
  12405. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12406. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12407. if (instancesCount) {
  12408. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12409. }
  12410. else {
  12411. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12412. }
  12413. };
  12414. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12415. // Apply states
  12416. this.applyStates();
  12417. this._drawCalls.addCount(1, false);
  12418. var drawMode = this.DrawMode(fillMode);
  12419. if (instancesCount) {
  12420. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12421. }
  12422. else {
  12423. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12424. }
  12425. };
  12426. Engine.prototype.DrawMode = function (fillMode) {
  12427. switch (fillMode) {
  12428. // Triangle views
  12429. case BABYLON.Material.TriangleFillMode:
  12430. return this._gl.TRIANGLES;
  12431. case BABYLON.Material.PointFillMode:
  12432. return this._gl.POINTS;
  12433. case BABYLON.Material.WireFrameFillMode:
  12434. return this._gl.LINES;
  12435. // Draw modes
  12436. case BABYLON.Material.PointListDrawMode:
  12437. return this._gl.POINTS;
  12438. case BABYLON.Material.LineListDrawMode:
  12439. return this._gl.LINES;
  12440. case BABYLON.Material.LineLoopDrawMode:
  12441. return this._gl.LINE_LOOP;
  12442. case BABYLON.Material.LineStripDrawMode:
  12443. return this._gl.LINE_STRIP;
  12444. case BABYLON.Material.TriangleStripDrawMode:
  12445. return this._gl.TRIANGLE_STRIP;
  12446. case BABYLON.Material.TriangleFanDrawMode:
  12447. return this._gl.TRIANGLE_FAN;
  12448. default:
  12449. return this._gl.TRIANGLES;
  12450. }
  12451. };
  12452. // Shaders
  12453. Engine.prototype._releaseEffect = function (effect) {
  12454. if (this._compiledEffects[effect._key]) {
  12455. delete this._compiledEffects[effect._key];
  12456. this._deleteProgram(effect.getProgram());
  12457. }
  12458. };
  12459. Engine.prototype._deleteProgram = function (program) {
  12460. if (program) {
  12461. program.__SPECTOR_rebuildProgram = null;
  12462. if (program.transformFeedback) {
  12463. this.deleteTransformFeedback(program.transformFeedback);
  12464. program.transformFeedback = null;
  12465. }
  12466. this._gl.deleteProgram(program);
  12467. }
  12468. };
  12469. /**
  12470. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12471. * @param samplers An array of string used to represent textures
  12472. */
  12473. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12474. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12475. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12476. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12477. if (this._compiledEffects[name]) {
  12478. var compiledEffect = this._compiledEffects[name];
  12479. if (onCompiled && compiledEffect.isReady()) {
  12480. onCompiled(compiledEffect);
  12481. }
  12482. return compiledEffect;
  12483. }
  12484. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12485. effect._key = name;
  12486. this._compiledEffects[name] = effect;
  12487. return effect;
  12488. };
  12489. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12490. if (uniformsNames === void 0) { uniformsNames = []; }
  12491. if (samplers === void 0) { samplers = []; }
  12492. if (defines === void 0) { defines = ""; }
  12493. return this.createEffect({
  12494. vertex: "particles",
  12495. fragmentElement: fragmentName
  12496. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12497. };
  12498. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12499. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12500. context = context || this._gl;
  12501. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12502. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12503. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12504. };
  12505. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12506. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12507. context = context || this._gl;
  12508. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12509. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12510. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12511. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12512. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12513. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12514. return program;
  12515. };
  12516. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12517. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12518. var shaderProgram = context.createProgram();
  12519. if (!shaderProgram) {
  12520. throw new Error("Unable to create program");
  12521. }
  12522. context.attachShader(shaderProgram, vertexShader);
  12523. context.attachShader(shaderProgram, fragmentShader);
  12524. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12525. var transformFeedback = this.createTransformFeedback();
  12526. this.bindTransformFeedback(transformFeedback);
  12527. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12528. shaderProgram.transformFeedback = transformFeedback;
  12529. }
  12530. context.linkProgram(shaderProgram);
  12531. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12532. this.bindTransformFeedback(null);
  12533. }
  12534. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12535. if (!linked) {
  12536. context.validateProgram(shaderProgram);
  12537. var error = context.getProgramInfoLog(shaderProgram);
  12538. if (error) {
  12539. throw new Error(error);
  12540. }
  12541. }
  12542. context.deleteShader(vertexShader);
  12543. context.deleteShader(fragmentShader);
  12544. return shaderProgram;
  12545. };
  12546. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12547. var results = new Array();
  12548. for (var index = 0; index < uniformsNames.length; index++) {
  12549. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12550. }
  12551. return results;
  12552. };
  12553. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12554. var results = [];
  12555. for (var index = 0; index < attributesNames.length; index++) {
  12556. try {
  12557. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12558. }
  12559. catch (e) {
  12560. results.push(-1);
  12561. }
  12562. }
  12563. return results;
  12564. };
  12565. Engine.prototype.enableEffect = function (effect) {
  12566. if (!effect) {
  12567. return;
  12568. }
  12569. // Use program
  12570. this.bindSamplers(effect);
  12571. this._currentEffect = effect;
  12572. if (effect.onBind) {
  12573. effect.onBind(effect);
  12574. }
  12575. effect.onBindObservable.notifyObservers(effect);
  12576. };
  12577. Engine.prototype.setIntArray = function (uniform, array) {
  12578. if (!uniform)
  12579. return;
  12580. this._gl.uniform1iv(uniform, array);
  12581. };
  12582. Engine.prototype.setIntArray2 = function (uniform, array) {
  12583. if (!uniform || array.length % 2 !== 0)
  12584. return;
  12585. this._gl.uniform2iv(uniform, array);
  12586. };
  12587. Engine.prototype.setIntArray3 = function (uniform, array) {
  12588. if (!uniform || array.length % 3 !== 0)
  12589. return;
  12590. this._gl.uniform3iv(uniform, array);
  12591. };
  12592. Engine.prototype.setIntArray4 = function (uniform, array) {
  12593. if (!uniform || array.length % 4 !== 0)
  12594. return;
  12595. this._gl.uniform4iv(uniform, array);
  12596. };
  12597. Engine.prototype.setFloatArray = function (uniform, array) {
  12598. if (!uniform)
  12599. return;
  12600. this._gl.uniform1fv(uniform, array);
  12601. };
  12602. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12603. if (!uniform || array.length % 2 !== 0)
  12604. return;
  12605. this._gl.uniform2fv(uniform, array);
  12606. };
  12607. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12608. if (!uniform || array.length % 3 !== 0)
  12609. return;
  12610. this._gl.uniform3fv(uniform, array);
  12611. };
  12612. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12613. if (!uniform || array.length % 4 !== 0)
  12614. return;
  12615. this._gl.uniform4fv(uniform, array);
  12616. };
  12617. Engine.prototype.setArray = function (uniform, array) {
  12618. if (!uniform)
  12619. return;
  12620. this._gl.uniform1fv(uniform, array);
  12621. };
  12622. Engine.prototype.setArray2 = function (uniform, array) {
  12623. if (!uniform || array.length % 2 !== 0)
  12624. return;
  12625. this._gl.uniform2fv(uniform, array);
  12626. };
  12627. Engine.prototype.setArray3 = function (uniform, array) {
  12628. if (!uniform || array.length % 3 !== 0)
  12629. return;
  12630. this._gl.uniform3fv(uniform, array);
  12631. };
  12632. Engine.prototype.setArray4 = function (uniform, array) {
  12633. if (!uniform || array.length % 4 !== 0)
  12634. return;
  12635. this._gl.uniform4fv(uniform, array);
  12636. };
  12637. Engine.prototype.setMatrices = function (uniform, matrices) {
  12638. if (!uniform)
  12639. return;
  12640. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12641. };
  12642. Engine.prototype.setMatrix = function (uniform, matrix) {
  12643. if (!uniform)
  12644. return;
  12645. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12646. };
  12647. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12648. if (!uniform)
  12649. return;
  12650. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12651. };
  12652. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12653. if (!uniform)
  12654. return;
  12655. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12656. };
  12657. Engine.prototype.setInt = function (uniform, value) {
  12658. if (!uniform)
  12659. return;
  12660. this._gl.uniform1i(uniform, value);
  12661. };
  12662. Engine.prototype.setFloat = function (uniform, value) {
  12663. if (!uniform)
  12664. return;
  12665. this._gl.uniform1f(uniform, value);
  12666. };
  12667. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12668. if (!uniform)
  12669. return;
  12670. this._gl.uniform2f(uniform, x, y);
  12671. };
  12672. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12673. if (!uniform)
  12674. return;
  12675. this._gl.uniform3f(uniform, x, y, z);
  12676. };
  12677. Engine.prototype.setBool = function (uniform, bool) {
  12678. if (!uniform)
  12679. return;
  12680. this._gl.uniform1i(uniform, bool);
  12681. };
  12682. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12683. if (!uniform)
  12684. return;
  12685. this._gl.uniform4f(uniform, x, y, z, w);
  12686. };
  12687. Engine.prototype.setColor3 = function (uniform, color3) {
  12688. if (!uniform)
  12689. return;
  12690. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12691. };
  12692. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12693. if (!uniform)
  12694. return;
  12695. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12696. };
  12697. /**
  12698. * Sets a Color4 on a uniform variable
  12699. * @param uniform defines the uniform location
  12700. * @param color4 defines the value to be set
  12701. */
  12702. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12703. if (!uniform)
  12704. return;
  12705. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12706. };
  12707. // States
  12708. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12709. if (zOffset === void 0) { zOffset = 0; }
  12710. if (reverseSide === void 0) { reverseSide = false; }
  12711. // Culling
  12712. if (this._depthCullingState.cull !== culling || force) {
  12713. this._depthCullingState.cull = culling;
  12714. }
  12715. // Cull face
  12716. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12717. if (this._depthCullingState.cullFace !== cullFace || force) {
  12718. this._depthCullingState.cullFace = cullFace;
  12719. }
  12720. // Z offset
  12721. this.setZOffset(zOffset);
  12722. // Front face
  12723. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12724. if (this._depthCullingState.frontFace !== frontFace || force) {
  12725. this._depthCullingState.frontFace = frontFace;
  12726. }
  12727. };
  12728. Engine.prototype.setZOffset = function (value) {
  12729. this._depthCullingState.zOffset = value;
  12730. };
  12731. Engine.prototype.getZOffset = function () {
  12732. return this._depthCullingState.zOffset;
  12733. };
  12734. Engine.prototype.setDepthBuffer = function (enable) {
  12735. this._depthCullingState.depthTest = enable;
  12736. };
  12737. Engine.prototype.getDepthWrite = function () {
  12738. return this._depthCullingState.depthMask;
  12739. };
  12740. Engine.prototype.setDepthWrite = function (enable) {
  12741. this._depthCullingState.depthMask = enable;
  12742. };
  12743. Engine.prototype.setColorWrite = function (enable) {
  12744. this._gl.colorMask(enable, enable, enable, enable);
  12745. this._colorWrite = enable;
  12746. };
  12747. Engine.prototype.getColorWrite = function () {
  12748. return this._colorWrite;
  12749. };
  12750. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12751. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12752. };
  12753. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12754. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12755. if (this._alphaMode === mode) {
  12756. return;
  12757. }
  12758. switch (mode) {
  12759. case Engine.ALPHA_DISABLE:
  12760. this._alphaState.alphaBlend = false;
  12761. break;
  12762. case Engine.ALPHA_PREMULTIPLIED:
  12763. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12764. this._alphaState.alphaBlend = true;
  12765. break;
  12766. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12767. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12768. this._alphaState.alphaBlend = true;
  12769. break;
  12770. case Engine.ALPHA_COMBINE:
  12771. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12772. this._alphaState.alphaBlend = true;
  12773. break;
  12774. case Engine.ALPHA_ONEONE:
  12775. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12776. this._alphaState.alphaBlend = true;
  12777. break;
  12778. case Engine.ALPHA_ADD:
  12779. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12780. this._alphaState.alphaBlend = true;
  12781. break;
  12782. case Engine.ALPHA_SUBTRACT:
  12783. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12784. this._alphaState.alphaBlend = true;
  12785. break;
  12786. case Engine.ALPHA_MULTIPLY:
  12787. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12788. this._alphaState.alphaBlend = true;
  12789. break;
  12790. case Engine.ALPHA_MAXIMIZED:
  12791. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12792. this._alphaState.alphaBlend = true;
  12793. break;
  12794. case Engine.ALPHA_INTERPOLATE:
  12795. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12796. this._alphaState.alphaBlend = true;
  12797. break;
  12798. case Engine.ALPHA_SCREENMODE:
  12799. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12800. this._alphaState.alphaBlend = true;
  12801. break;
  12802. }
  12803. if (!noDepthWriteChange) {
  12804. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12805. }
  12806. this._alphaMode = mode;
  12807. };
  12808. Engine.prototype.getAlphaMode = function () {
  12809. return this._alphaMode;
  12810. };
  12811. // Textures
  12812. Engine.prototype.wipeCaches = function (bruteForce) {
  12813. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12814. return;
  12815. }
  12816. this._currentEffect = null;
  12817. // 6/8/2017: deltakosh: Should not be required anymore.
  12818. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12819. if (bruteForce) {
  12820. this.resetTextureCache();
  12821. this._currentProgram = null;
  12822. this._stencilState.reset();
  12823. this._depthCullingState.reset();
  12824. this.setDepthFunctionToLessOrEqual();
  12825. this._alphaState.reset();
  12826. }
  12827. this._resetVertexBufferBinding();
  12828. this._cachedIndexBuffer = null;
  12829. this._cachedEffectForVertexBuffers = null;
  12830. this._unbindVertexArrayObject();
  12831. this.bindIndexBuffer(null);
  12832. };
  12833. /**
  12834. * Set the compressed texture format to use, based on the formats you have, and the formats
  12835. * supported by the hardware / browser.
  12836. *
  12837. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12838. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12839. * to API arguments needed to compressed textures. This puts the burden on the container
  12840. * generator to house the arcane code for determining these for current & future formats.
  12841. *
  12842. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12843. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12844. *
  12845. * Note: The result of this call is not taken into account when a texture is base64.
  12846. *
  12847. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12848. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12849. *
  12850. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12851. * @returns The extension selected.
  12852. */
  12853. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12854. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12855. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12856. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12857. return this._textureFormatInUse = this._texturesSupported[i];
  12858. }
  12859. }
  12860. }
  12861. // actively set format to nothing, to allow this to be called more than once
  12862. // and possibly fail the 2nd time
  12863. this._textureFormatInUse = null;
  12864. return null;
  12865. };
  12866. Engine.prototype._createTexture = function () {
  12867. var texture = this._gl.createTexture();
  12868. if (!texture) {
  12869. throw new Error("Unable to create texture");
  12870. }
  12871. return texture;
  12872. };
  12873. /**
  12874. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12875. * @param {string} urlArg- This contains one of the following:
  12876. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12877. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12878. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12879. *
  12880. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12881. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12882. * @param {Scene} scene- Needed for loading to the correct scene.
  12883. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12884. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12885. * @param {callback} onError- Optional callback to be called upon failure.
  12886. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12887. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12888. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12889. *
  12890. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12891. */
  12892. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12893. var _this = this;
  12894. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12895. if (onLoad === void 0) { onLoad = null; }
  12896. if (onError === void 0) { onError = null; }
  12897. if (buffer === void 0) { buffer = null; }
  12898. if (fallBack === void 0) { fallBack = null; }
  12899. if (format === void 0) { format = null; }
  12900. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12901. var fromData = url.substr(0, 5) === "data:";
  12902. var fromBlob = url.substr(0, 5) === "blob:";
  12903. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12904. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12905. // establish the file extension, if possible
  12906. var lastDot = url.lastIndexOf('.');
  12907. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12908. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12909. var isTGA = (extension.indexOf(".tga") === 0);
  12910. // determine if a ktx file should be substituted
  12911. var isKTX = false;
  12912. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12913. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12914. isKTX = true;
  12915. }
  12916. if (scene) {
  12917. scene._addPendingData(texture);
  12918. }
  12919. texture.url = url;
  12920. texture.generateMipMaps = !noMipmap;
  12921. texture.samplingMode = samplingMode;
  12922. texture.invertY = invertY;
  12923. if (!this._doNotHandleContextLost) {
  12924. // Keep a link to the buffer only if we plan to handle context lost
  12925. texture._buffer = buffer;
  12926. }
  12927. var onLoadObserver = null;
  12928. if (onLoad && !fallBack) {
  12929. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12930. }
  12931. if (!fallBack)
  12932. this._internalTexturesCache.push(texture);
  12933. var onerror = function (message, exception) {
  12934. if (scene) {
  12935. scene._removePendingData(texture);
  12936. }
  12937. if (onLoadObserver) {
  12938. texture.onLoadedObservable.remove(onLoadObserver);
  12939. }
  12940. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12941. if (isKTX) {
  12942. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12943. }
  12944. else if (BABYLON.Tools.UseFallbackTexture) {
  12945. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12946. }
  12947. if (onError) {
  12948. onError(message || "Unknown error", exception);
  12949. }
  12950. };
  12951. var callback = null;
  12952. // processing for non-image formats
  12953. if (isKTX || isTGA || isDDS) {
  12954. if (isKTX) {
  12955. callback = function (data) {
  12956. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12957. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12958. ktx.uploadLevels(_this._gl, !noMipmap);
  12959. return false;
  12960. }, samplingMode);
  12961. };
  12962. }
  12963. else if (isTGA) {
  12964. callback = function (arrayBuffer) {
  12965. var data = new Uint8Array(arrayBuffer);
  12966. var header = BABYLON.TGATools.GetTGAHeader(data);
  12967. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12968. BABYLON.TGATools.UploadContent(_this._gl, data);
  12969. return false;
  12970. }, samplingMode);
  12971. };
  12972. }
  12973. else if (isDDS) {
  12974. callback = function (data) {
  12975. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12976. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12977. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12978. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12979. return false;
  12980. }, samplingMode);
  12981. };
  12982. }
  12983. if (!buffer) {
  12984. this._loadFile(url, function (data) {
  12985. if (callback) {
  12986. callback(data);
  12987. }
  12988. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12989. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12990. });
  12991. }
  12992. else {
  12993. if (callback) {
  12994. callback(buffer);
  12995. }
  12996. }
  12997. // image format processing
  12998. }
  12999. else {
  13000. var onload = function (img) {
  13001. if (fromBlob && !_this._doNotHandleContextLost) {
  13002. // We need to store the image if we need to rebuild the texture
  13003. // in case of a webgl context lost
  13004. texture._buffer = img;
  13005. }
  13006. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13007. var gl = _this._gl;
  13008. var isPot = (img.width === potWidth && img.height === potHeight);
  13009. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13010. if (isPot) {
  13011. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13012. return false;
  13013. }
  13014. // Using shaders to rescale because canvas.drawImage is lossy
  13015. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13016. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13017. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13022. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13023. _this._releaseTexture(source);
  13024. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13025. continuationCallback();
  13026. });
  13027. return true;
  13028. }, samplingMode);
  13029. };
  13030. if (!fromData || isBase64)
  13031. if (buffer instanceof HTMLImageElement) {
  13032. onload(buffer);
  13033. }
  13034. else {
  13035. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13036. }
  13037. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13038. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13039. else
  13040. onload(buffer);
  13041. }
  13042. return texture;
  13043. };
  13044. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13045. var _this = this;
  13046. var rtt = this.createRenderTargetTexture({
  13047. width: destination.width,
  13048. height: destination.height,
  13049. }, {
  13050. generateMipMaps: false,
  13051. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13052. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13053. generateDepthBuffer: false,
  13054. generateStencilBuffer: false
  13055. });
  13056. if (!this._rescalePostProcess) {
  13057. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13058. }
  13059. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13060. _this._rescalePostProcess.onApply = function (effect) {
  13061. effect._bindTexture("textureSampler", source);
  13062. };
  13063. var hostingScene = scene;
  13064. if (!hostingScene) {
  13065. hostingScene = _this.scenes[_this.scenes.length - 1];
  13066. }
  13067. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13068. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13069. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13070. _this.unBindFramebuffer(rtt);
  13071. _this._releaseTexture(rtt);
  13072. if (onComplete) {
  13073. onComplete();
  13074. }
  13075. });
  13076. };
  13077. Engine.prototype._getInternalFormat = function (format) {
  13078. var internalFormat = this._gl.RGBA;
  13079. switch (format) {
  13080. case Engine.TEXTUREFORMAT_ALPHA:
  13081. internalFormat = this._gl.ALPHA;
  13082. break;
  13083. case Engine.TEXTUREFORMAT_LUMINANCE:
  13084. internalFormat = this._gl.LUMINANCE;
  13085. break;
  13086. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13087. internalFormat = this._gl.LUMINANCE_ALPHA;
  13088. break;
  13089. case Engine.TEXTUREFORMAT_RGB:
  13090. case Engine.TEXTUREFORMAT_RGB32F:
  13091. internalFormat = this._gl.RGB;
  13092. break;
  13093. case Engine.TEXTUREFORMAT_RGBA:
  13094. case Engine.TEXTUREFORMAT_RGBA32F:
  13095. internalFormat = this._gl.RGBA;
  13096. break;
  13097. case Engine.TEXTUREFORMAT_R32F:
  13098. internalFormat = this._gl.RED;
  13099. break;
  13100. case Engine.TEXTUREFORMAT_RG32F:
  13101. internalFormat = this._gl.RG;
  13102. break;
  13103. }
  13104. return internalFormat;
  13105. };
  13106. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13107. if (compression === void 0) { compression = null; }
  13108. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13109. if (!texture) {
  13110. return;
  13111. }
  13112. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13113. var internalFormat = this._getInternalFormat(format);
  13114. var textureType = this._getWebGLTextureType(type);
  13115. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13116. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13117. if (!this._doNotHandleContextLost) {
  13118. texture._bufferView = data;
  13119. texture.format = format;
  13120. texture.type = type;
  13121. texture.invertY = invertY;
  13122. texture._compression = compression;
  13123. }
  13124. if (texture.width % 4 !== 0) {
  13125. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13126. }
  13127. if (compression && data) {
  13128. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13129. }
  13130. else {
  13131. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13132. }
  13133. if (texture.generateMipMaps) {
  13134. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13135. }
  13136. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13137. // this.resetTextureCache();
  13138. texture.isReady = true;
  13139. };
  13140. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13141. if (compression === void 0) { compression = null; }
  13142. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13143. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13144. texture.baseWidth = width;
  13145. texture.baseHeight = height;
  13146. texture.width = width;
  13147. texture.height = height;
  13148. texture.format = format;
  13149. texture.generateMipMaps = generateMipMaps;
  13150. texture.samplingMode = samplingMode;
  13151. texture.invertY = invertY;
  13152. texture._compression = compression;
  13153. texture.type = type;
  13154. if (!this._doNotHandleContextLost) {
  13155. texture._bufferView = data;
  13156. }
  13157. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13158. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13159. // Filters
  13160. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13161. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13162. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13163. if (generateMipMaps) {
  13164. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13165. }
  13166. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13167. this._internalTexturesCache.push(texture);
  13168. return texture;
  13169. };
  13170. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13171. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13172. texture.baseWidth = width;
  13173. texture.baseHeight = height;
  13174. if (generateMipMaps) {
  13175. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13176. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13177. }
  13178. // this.resetTextureCache();
  13179. texture.width = width;
  13180. texture.height = height;
  13181. texture.isReady = false;
  13182. texture.generateMipMaps = generateMipMaps;
  13183. texture.samplingMode = samplingMode;
  13184. this.updateTextureSamplingMode(samplingMode, texture);
  13185. this._internalTexturesCache.push(texture);
  13186. return texture;
  13187. };
  13188. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13189. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13190. if (texture.isCube) {
  13191. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13192. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13193. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13194. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13195. }
  13196. else if (texture.is3D) {
  13197. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13198. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13199. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13200. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13201. }
  13202. else {
  13203. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  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. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13207. }
  13208. texture.samplingMode = samplingMode;
  13209. };
  13210. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13211. if (premulAlpha === void 0) { premulAlpha = false; }
  13212. if (!texture) {
  13213. return;
  13214. }
  13215. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13216. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13217. if (premulAlpha) {
  13218. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13219. }
  13220. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13221. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13222. if (texture.generateMipMaps) {
  13223. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13224. }
  13225. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13226. if (premulAlpha) {
  13227. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13228. }
  13229. texture.isReady = true;
  13230. };
  13231. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13232. if (!texture || texture._isDisabled) {
  13233. return;
  13234. }
  13235. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13236. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13237. try {
  13238. // Testing video texture support
  13239. if (this._videoTextureSupported === undefined) {
  13240. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13241. if (this._gl.getError() !== 0) {
  13242. this._videoTextureSupported = false;
  13243. }
  13244. else {
  13245. this._videoTextureSupported = true;
  13246. }
  13247. }
  13248. // Copy video through the current working canvas if video texture is not supported
  13249. if (!this._videoTextureSupported) {
  13250. if (!texture._workingCanvas) {
  13251. texture._workingCanvas = document.createElement("canvas");
  13252. var context = texture._workingCanvas.getContext("2d");
  13253. if (!context) {
  13254. throw new Error("Unable to get 2d context");
  13255. }
  13256. texture._workingContext = context;
  13257. texture._workingCanvas.width = texture.width;
  13258. texture._workingCanvas.height = texture.height;
  13259. }
  13260. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13261. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13262. }
  13263. else {
  13264. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13265. }
  13266. if (texture.generateMipMaps) {
  13267. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13268. }
  13269. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13270. // this.resetTextureCache();
  13271. texture.isReady = true;
  13272. }
  13273. catch (ex) {
  13274. // Something unexpected
  13275. // Let's disable the texture
  13276. texture._isDisabled = true;
  13277. }
  13278. };
  13279. /**
  13280. * Updates a depth texture Comparison Mode and Function.
  13281. * If the comparison Function is equal to 0, the mode will be set to none.
  13282. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13283. * @param texture The texture to set the comparison function for
  13284. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13285. */
  13286. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13287. if (this.webGLVersion === 1) {
  13288. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13289. return;
  13290. }
  13291. var gl = this._gl;
  13292. if (texture.isCube) {
  13293. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13294. if (comparisonFunction === 0) {
  13295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13297. }
  13298. else {
  13299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13301. }
  13302. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13303. }
  13304. else {
  13305. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13306. if (comparisonFunction === 0) {
  13307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13309. }
  13310. else {
  13311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13313. }
  13314. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13315. }
  13316. texture._comparisonFunction = comparisonFunction;
  13317. };
  13318. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13319. var width = size.width || size;
  13320. var height = size.height || size;
  13321. internalTexture.baseWidth = width;
  13322. internalTexture.baseHeight = height;
  13323. internalTexture.width = width;
  13324. internalTexture.height = height;
  13325. internalTexture.isReady = true;
  13326. internalTexture.samples = 1;
  13327. internalTexture.generateMipMaps = false;
  13328. internalTexture._generateDepthBuffer = true;
  13329. internalTexture._generateStencilBuffer = generateStencil;
  13330. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13331. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13332. internalTexture._comparisonFunction = comparisonFunction;
  13333. var gl = this._gl;
  13334. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13335. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13336. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13337. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13338. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13339. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13340. if (comparisonFunction === 0) {
  13341. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13342. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13343. }
  13344. else {
  13345. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13346. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13347. }
  13348. };
  13349. /**
  13350. * Creates a depth stencil texture.
  13351. * This is only available in WebGL 2 or with the depth texture extension available.
  13352. * @param size The size of face edge in the texture.
  13353. * @param options The options defining the texture.
  13354. * @returns The texture
  13355. */
  13356. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13357. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13358. if (!this._caps.depthTextureExtension) {
  13359. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13360. return internalTexture;
  13361. }
  13362. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13363. var gl = this._gl;
  13364. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13365. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13366. if (this.webGLVersion > 1) {
  13367. if (internalOptions.generateStencil) {
  13368. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13369. }
  13370. else {
  13371. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13372. }
  13373. }
  13374. else {
  13375. if (internalOptions.generateStencil) {
  13376. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13377. }
  13378. else {
  13379. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13380. }
  13381. }
  13382. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13383. return internalTexture;
  13384. };
  13385. /**
  13386. * Creates a depth stencil cube texture.
  13387. * This is only available in WebGL 2.
  13388. * @param size The size of face edge in the cube texture.
  13389. * @param options The options defining the cube texture.
  13390. * @returns The cube texture
  13391. */
  13392. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13393. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13394. internalTexture.isCube = true;
  13395. if (this.webGLVersion === 1) {
  13396. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13397. return internalTexture;
  13398. }
  13399. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13400. var gl = this._gl;
  13401. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13402. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13403. // Create the depth/stencil buffer
  13404. for (var face = 0; face < 6; face++) {
  13405. if (internalOptions.generateStencil) {
  13406. 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);
  13407. }
  13408. else {
  13409. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13410. }
  13411. }
  13412. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13413. return internalTexture;
  13414. };
  13415. /**
  13416. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13417. * @param renderTarget The render target to set the frame buffer for
  13418. */
  13419. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13420. // Create the framebuffer
  13421. var internalTexture = renderTarget.getInternalTexture();
  13422. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13423. return;
  13424. }
  13425. var gl = this._gl;
  13426. var depthStencilTexture = renderTarget.depthStencilTexture;
  13427. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13428. if (depthStencilTexture.isCube) {
  13429. if (depthStencilTexture._generateStencilBuffer) {
  13430. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13431. }
  13432. else {
  13433. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13434. }
  13435. }
  13436. else {
  13437. if (depthStencilTexture._generateStencilBuffer) {
  13438. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13439. }
  13440. else {
  13441. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13442. }
  13443. }
  13444. this.bindUnboundFramebuffer(null);
  13445. };
  13446. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13447. var fullOptions = new RenderTargetCreationOptions();
  13448. if (options !== undefined && typeof options === "object") {
  13449. fullOptions.generateMipMaps = options.generateMipMaps;
  13450. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13451. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13452. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13453. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13454. }
  13455. else {
  13456. fullOptions.generateMipMaps = options;
  13457. fullOptions.generateDepthBuffer = true;
  13458. fullOptions.generateStencilBuffer = false;
  13459. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13460. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13461. }
  13462. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13463. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13464. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13465. }
  13466. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13467. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13468. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13469. }
  13470. var gl = this._gl;
  13471. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13472. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13473. var width = size.width || size;
  13474. var height = size.height || size;
  13475. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13476. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13477. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13478. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13479. }
  13480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13484. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13485. // Create the framebuffer
  13486. var framebuffer = gl.createFramebuffer();
  13487. this.bindUnboundFramebuffer(framebuffer);
  13488. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13489. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13490. if (fullOptions.generateMipMaps) {
  13491. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13492. }
  13493. // Unbind
  13494. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13495. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13496. this.bindUnboundFramebuffer(null);
  13497. texture._framebuffer = framebuffer;
  13498. texture.baseWidth = width;
  13499. texture.baseHeight = height;
  13500. texture.width = width;
  13501. texture.height = height;
  13502. texture.isReady = true;
  13503. texture.samples = 1;
  13504. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13505. texture.samplingMode = fullOptions.samplingMode;
  13506. texture.type = fullOptions.type;
  13507. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13508. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13509. // this.resetTextureCache();
  13510. this._internalTexturesCache.push(texture);
  13511. return texture;
  13512. };
  13513. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13514. var generateMipMaps = false;
  13515. var generateDepthBuffer = true;
  13516. var generateStencilBuffer = false;
  13517. var generateDepthTexture = false;
  13518. var textureCount = 1;
  13519. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13520. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13521. var types = [], samplingModes = [];
  13522. if (options !== undefined) {
  13523. generateMipMaps = options.generateMipMaps;
  13524. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13525. generateStencilBuffer = options.generateStencilBuffer;
  13526. generateDepthTexture = options.generateDepthTexture;
  13527. textureCount = options.textureCount || 1;
  13528. if (options.types) {
  13529. types = options.types;
  13530. }
  13531. if (options.samplingModes) {
  13532. samplingModes = options.samplingModes;
  13533. }
  13534. }
  13535. var gl = this._gl;
  13536. // Create the framebuffer
  13537. var framebuffer = gl.createFramebuffer();
  13538. this.bindUnboundFramebuffer(framebuffer);
  13539. var width = size.width || size;
  13540. var height = size.height || size;
  13541. var textures = [];
  13542. var attachments = [];
  13543. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13544. for (var i = 0; i < textureCount; i++) {
  13545. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13546. var type = types[i] || defaultType;
  13547. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13548. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13549. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13550. }
  13551. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13552. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13553. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13554. }
  13555. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13556. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13557. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13558. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13559. }
  13560. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13561. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13562. textures.push(texture);
  13563. attachments.push(attachment);
  13564. gl.activeTexture(gl["TEXTURE" + i]);
  13565. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13570. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13571. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13572. if (generateMipMaps) {
  13573. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13574. }
  13575. // Unbind
  13576. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13577. texture._framebuffer = framebuffer;
  13578. texture._depthStencilBuffer = depthStencilBuffer;
  13579. texture.baseWidth = width;
  13580. texture.baseHeight = height;
  13581. texture.width = width;
  13582. texture.height = height;
  13583. texture.isReady = true;
  13584. texture.samples = 1;
  13585. texture.generateMipMaps = generateMipMaps;
  13586. texture.samplingMode = samplingMode;
  13587. texture.type = type;
  13588. texture._generateDepthBuffer = generateDepthBuffer;
  13589. texture._generateStencilBuffer = generateStencilBuffer;
  13590. texture._attachments = attachments;
  13591. this._internalTexturesCache.push(texture);
  13592. }
  13593. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13594. // Depth texture
  13595. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13596. gl.activeTexture(gl.TEXTURE0);
  13597. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13598. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13599. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13600. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13601. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13602. 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);
  13603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13604. depthTexture._framebuffer = framebuffer;
  13605. depthTexture.baseWidth = width;
  13606. depthTexture.baseHeight = height;
  13607. depthTexture.width = width;
  13608. depthTexture.height = height;
  13609. depthTexture.isReady = true;
  13610. depthTexture.samples = 1;
  13611. depthTexture.generateMipMaps = generateMipMaps;
  13612. depthTexture.samplingMode = gl.NEAREST;
  13613. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13614. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13615. textures.push(depthTexture);
  13616. this._internalTexturesCache.push(depthTexture);
  13617. }
  13618. gl.drawBuffers(attachments);
  13619. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13620. this.bindUnboundFramebuffer(null);
  13621. this.resetTextureCache();
  13622. return textures;
  13623. };
  13624. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13625. if (samples === void 0) { samples = 1; }
  13626. var depthStencilBuffer = null;
  13627. var gl = this._gl;
  13628. // Create the depth/stencil buffer
  13629. if (generateStencilBuffer) {
  13630. depthStencilBuffer = gl.createRenderbuffer();
  13631. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13632. if (samples > 1) {
  13633. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13634. }
  13635. else {
  13636. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13637. }
  13638. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13639. }
  13640. else if (generateDepthBuffer) {
  13641. depthStencilBuffer = gl.createRenderbuffer();
  13642. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13643. if (samples > 1) {
  13644. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13645. }
  13646. else {
  13647. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13648. }
  13649. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13650. }
  13651. return depthStencilBuffer;
  13652. };
  13653. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13654. if (this.webGLVersion < 2 || !texture) {
  13655. return 1;
  13656. }
  13657. if (texture.samples === samples) {
  13658. return samples;
  13659. }
  13660. var gl = this._gl;
  13661. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13662. // Dispose previous render buffers
  13663. if (texture._depthStencilBuffer) {
  13664. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13665. texture._depthStencilBuffer = null;
  13666. }
  13667. if (texture._MSAAFramebuffer) {
  13668. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13669. texture._MSAAFramebuffer = null;
  13670. }
  13671. if (texture._MSAARenderBuffer) {
  13672. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13673. texture._MSAARenderBuffer = null;
  13674. }
  13675. if (samples > 1) {
  13676. var framebuffer = gl.createFramebuffer();
  13677. if (!framebuffer) {
  13678. throw new Error("Unable to create multi sampled framebuffer");
  13679. }
  13680. texture._MSAAFramebuffer = framebuffer;
  13681. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13682. var colorRenderbuffer = gl.createRenderbuffer();
  13683. if (!colorRenderbuffer) {
  13684. throw new Error("Unable to create multi sampled framebuffer");
  13685. }
  13686. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13687. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13688. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13689. texture._MSAARenderBuffer = colorRenderbuffer;
  13690. }
  13691. else {
  13692. this.bindUnboundFramebuffer(texture._framebuffer);
  13693. }
  13694. texture.samples = samples;
  13695. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13696. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13697. this.bindUnboundFramebuffer(null);
  13698. return samples;
  13699. };
  13700. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13701. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13702. return 1;
  13703. }
  13704. if (textures[0].samples === samples) {
  13705. return samples;
  13706. }
  13707. var gl = this._gl;
  13708. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13709. // Dispose previous render buffers
  13710. if (textures[0]._depthStencilBuffer) {
  13711. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13712. textures[0]._depthStencilBuffer = null;
  13713. }
  13714. if (textures[0]._MSAAFramebuffer) {
  13715. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13716. textures[0]._MSAAFramebuffer = null;
  13717. }
  13718. for (var i = 0; i < textures.length; i++) {
  13719. if (textures[i]._MSAARenderBuffer) {
  13720. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13721. textures[i]._MSAARenderBuffer = null;
  13722. }
  13723. }
  13724. if (samples > 1) {
  13725. var framebuffer = gl.createFramebuffer();
  13726. if (!framebuffer) {
  13727. throw new Error("Unable to create multi sampled framebuffer");
  13728. }
  13729. this.bindUnboundFramebuffer(framebuffer);
  13730. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13731. var attachments = [];
  13732. for (var i = 0; i < textures.length; i++) {
  13733. var texture = textures[i];
  13734. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13735. var colorRenderbuffer = gl.createRenderbuffer();
  13736. if (!colorRenderbuffer) {
  13737. throw new Error("Unable to create multi sampled framebuffer");
  13738. }
  13739. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13740. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13741. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13742. texture._MSAAFramebuffer = framebuffer;
  13743. texture._MSAARenderBuffer = colorRenderbuffer;
  13744. texture.samples = samples;
  13745. texture._depthStencilBuffer = depthStencilBuffer;
  13746. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13747. attachments.push(attachment);
  13748. }
  13749. gl.drawBuffers(attachments);
  13750. }
  13751. else {
  13752. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13753. }
  13754. this.bindUnboundFramebuffer(null);
  13755. return samples;
  13756. };
  13757. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13758. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13759. };
  13760. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13761. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13762. };
  13763. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13764. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13765. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13766. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13767. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13768. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13769. }
  13770. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13771. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13772. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13773. }
  13774. var gl = this._gl;
  13775. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13776. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13777. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13778. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13779. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13780. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13781. }
  13782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13786. for (var face = 0; face < 6; face++) {
  13787. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13788. }
  13789. // Create the framebuffer
  13790. var framebuffer = gl.createFramebuffer();
  13791. this.bindUnboundFramebuffer(framebuffer);
  13792. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13793. // MipMaps
  13794. if (fullOptions.generateMipMaps) {
  13795. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13796. }
  13797. // Unbind
  13798. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13799. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13800. this.bindUnboundFramebuffer(null);
  13801. texture._framebuffer = framebuffer;
  13802. texture.width = size;
  13803. texture.height = size;
  13804. texture.isReady = true;
  13805. texture.isCube = true;
  13806. texture.samples = 1;
  13807. texture.generateMipMaps = fullOptions.generateMipMaps;
  13808. texture.samplingMode = fullOptions.samplingMode;
  13809. texture.type = fullOptions.type;
  13810. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13811. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13812. this._internalTexturesCache.push(texture);
  13813. return texture;
  13814. };
  13815. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13816. var _this = this;
  13817. if (onLoad === void 0) { onLoad = null; }
  13818. if (onError === void 0) { onError = null; }
  13819. if (forcedExtension === void 0) { forcedExtension = null; }
  13820. var callback = function (loadData) {
  13821. if (!loadData) {
  13822. if (onLoad) {
  13823. onLoad(null);
  13824. }
  13825. return;
  13826. }
  13827. var texture = loadData.texture;
  13828. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13829. texture._lodGenerationScale = scale;
  13830. texture._lodGenerationOffset = offset;
  13831. if (_this._caps.textureLOD) {
  13832. // Do not add extra process if texture lod is supported.
  13833. if (onLoad) {
  13834. onLoad(texture);
  13835. }
  13836. return;
  13837. }
  13838. var mipSlices = 3;
  13839. var gl = _this._gl;
  13840. var width = loadData.width;
  13841. if (!width) {
  13842. return;
  13843. }
  13844. var textures = [];
  13845. for (var i = 0; i < mipSlices; i++) {
  13846. //compute LOD from even spacing in smoothness (matching shader calculation)
  13847. var smoothness = i / (mipSlices - 1);
  13848. var roughness = 1 - smoothness;
  13849. var minLODIndex = offset; // roughness = 0
  13850. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13851. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13852. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13853. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13854. glTextureFromLod.isCube = true;
  13855. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13859. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13860. if (loadData.isDDS) {
  13861. var info = loadData.info;
  13862. var data = loadData.data;
  13863. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13864. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13865. }
  13866. else {
  13867. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13868. }
  13869. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13870. // Wrap in a base texture for easy binding.
  13871. var lodTexture = new BABYLON.BaseTexture(scene);
  13872. lodTexture.isCube = true;
  13873. lodTexture._texture = glTextureFromLod;
  13874. glTextureFromLod.isReady = true;
  13875. textures.push(lodTexture);
  13876. }
  13877. texture._lodTextureHigh = textures[2];
  13878. texture._lodTextureMid = textures[1];
  13879. texture._lodTextureLow = textures[0];
  13880. if (onLoad) {
  13881. onLoad(texture);
  13882. }
  13883. };
  13884. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13885. };
  13886. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13887. var _this = this;
  13888. if (onLoad === void 0) { onLoad = null; }
  13889. if (onError === void 0) { onError = null; }
  13890. if (forcedExtension === void 0) { forcedExtension = null; }
  13891. var gl = this._gl;
  13892. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13893. texture.isCube = true;
  13894. texture.url = rootUrl;
  13895. texture.generateMipMaps = !noMipmap;
  13896. if (!this._doNotHandleContextLost) {
  13897. texture._extension = forcedExtension;
  13898. texture._files = files;
  13899. }
  13900. var isKTX = false;
  13901. var isDDS = false;
  13902. var lastDot = rootUrl.lastIndexOf('.');
  13903. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13904. if (this._textureFormatInUse) {
  13905. extension = this._textureFormatInUse;
  13906. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13907. isKTX = true;
  13908. }
  13909. else {
  13910. isDDS = (extension === ".dds");
  13911. }
  13912. var onerror = function (request, exception) {
  13913. if (onError && request) {
  13914. onError(request.status + " " + request.statusText, exception);
  13915. }
  13916. };
  13917. if (isKTX) {
  13918. this._loadFile(rootUrl, function (data) {
  13919. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13920. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13921. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13922. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13923. ktx.uploadLevels(_this._gl, !noMipmap);
  13924. _this.setCubeMapTextureParams(gl, loadMipmap);
  13925. texture.width = ktx.pixelWidth;
  13926. texture.height = ktx.pixelHeight;
  13927. texture.isReady = true;
  13928. }, undefined, undefined, true, onerror);
  13929. }
  13930. else if (isDDS) {
  13931. if (files && files.length === 6) {
  13932. this._cascadeLoadFiles(scene, function (imgs) {
  13933. var info;
  13934. var loadMipmap = false;
  13935. var width = 0;
  13936. for (var index = 0; index < imgs.length; index++) {
  13937. var data = imgs[index];
  13938. info = BABYLON.DDSTools.GetDDSInfo(data);
  13939. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13940. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13941. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13942. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13943. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13944. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13945. }
  13946. texture.width = info.width;
  13947. texture.height = info.height;
  13948. texture.type = info.textureType;
  13949. width = info.width;
  13950. }
  13951. _this.setCubeMapTextureParams(gl, loadMipmap);
  13952. texture.isReady = true;
  13953. if (onLoad) {
  13954. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13955. }
  13956. }, files, onError);
  13957. }
  13958. else {
  13959. this._loadFile(rootUrl, function (data) {
  13960. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13961. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13962. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13963. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13964. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13965. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13966. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13967. }
  13968. _this.setCubeMapTextureParams(gl, loadMipmap);
  13969. texture.width = info.width;
  13970. texture.height = info.height;
  13971. texture.isReady = true;
  13972. texture.type = info.textureType;
  13973. if (onLoad) {
  13974. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13975. }
  13976. }, undefined, undefined, true, onerror);
  13977. }
  13978. }
  13979. else {
  13980. if (!files) {
  13981. throw new Error("Cannot load cubemap because files were not defined");
  13982. }
  13983. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13984. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13985. var height = width;
  13986. _this._prepareWorkingCanvas();
  13987. if (!_this._workingCanvas || !_this._workingContext) {
  13988. return;
  13989. }
  13990. _this._workingCanvas.width = width;
  13991. _this._workingCanvas.height = height;
  13992. var faces = [
  13993. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13994. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13995. ];
  13996. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13997. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13998. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13999. for (var index = 0; index < faces.length; index++) {
  14000. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14001. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14002. }
  14003. if (!noMipmap) {
  14004. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14005. }
  14006. _this.setCubeMapTextureParams(gl, !noMipmap);
  14007. texture.width = width;
  14008. texture.height = height;
  14009. texture.isReady = true;
  14010. if (format) {
  14011. texture.format = format;
  14012. }
  14013. texture.onLoadedObservable.notifyObservers(texture);
  14014. texture.onLoadedObservable.clear();
  14015. if (onLoad) {
  14016. onLoad();
  14017. }
  14018. }, files, onError);
  14019. }
  14020. this._internalTexturesCache.push(texture);
  14021. return texture;
  14022. };
  14023. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14024. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14025. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14026. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14027. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14028. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14029. // this.resetTextureCache();
  14030. };
  14031. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14032. if (compression === void 0) { compression = null; }
  14033. if (level === void 0) { level = 0; }
  14034. texture._bufferViewArray = data;
  14035. texture.format = format;
  14036. texture.type = type;
  14037. texture.invertY = invertY;
  14038. texture._compression = compression;
  14039. var gl = this._gl;
  14040. var textureType = this._getWebGLTextureType(type);
  14041. var internalFormat = this._getInternalFormat(format);
  14042. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14043. var needConversion = false;
  14044. if (internalFormat === gl.RGB) {
  14045. internalFormat = gl.RGBA;
  14046. needConversion = true;
  14047. }
  14048. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14049. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14050. if (texture.width % 4 !== 0) {
  14051. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14052. }
  14053. // Data are known to be in +X +Y +Z -X -Y -Z
  14054. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14055. var faceData = data[faceIndex];
  14056. if (compression) {
  14057. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14058. }
  14059. else {
  14060. if (needConversion) {
  14061. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14062. }
  14063. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14064. }
  14065. }
  14066. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14067. if (isPot && texture.generateMipMaps && level === 0) {
  14068. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14069. }
  14070. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14071. // this.resetTextureCache();
  14072. texture.isReady = true;
  14073. };
  14074. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14075. if (compression === void 0) { compression = null; }
  14076. var gl = this._gl;
  14077. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14078. texture.isCube = true;
  14079. texture.generateMipMaps = generateMipMaps;
  14080. texture.format = format;
  14081. texture.type = type;
  14082. if (!this._doNotHandleContextLost) {
  14083. texture._bufferViewArray = data;
  14084. }
  14085. var textureType = this._getWebGLTextureType(type);
  14086. var internalFormat = this._getInternalFormat(format);
  14087. if (internalFormat === gl.RGB) {
  14088. internalFormat = gl.RGBA;
  14089. }
  14090. var width = size;
  14091. var height = width;
  14092. texture.width = width;
  14093. texture.height = height;
  14094. // Double check on POT to generate Mips.
  14095. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14096. if (!isPot) {
  14097. generateMipMaps = false;
  14098. }
  14099. // Upload data if needed. The texture won't be ready until then.
  14100. if (data) {
  14101. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14102. }
  14103. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14104. // Filters
  14105. if (data && generateMipMaps) {
  14106. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14107. }
  14108. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14110. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14111. }
  14112. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14115. }
  14116. else {
  14117. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14120. }
  14121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14123. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14124. return texture;
  14125. };
  14126. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14127. var _this = this;
  14128. if (onLoad === void 0) { onLoad = null; }
  14129. if (onError === void 0) { onError = null; }
  14130. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14131. if (invertY === void 0) { invertY = false; }
  14132. var gl = this._gl;
  14133. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14134. scene._addPendingData(texture);
  14135. texture.url = url;
  14136. this._internalTexturesCache.push(texture);
  14137. var onerror = function (request, exception) {
  14138. scene._removePendingData(texture);
  14139. if (onError && request) {
  14140. onError(request.status + " " + request.statusText, exception);
  14141. }
  14142. };
  14143. var internalCallback = function (data) {
  14144. var width = texture.width;
  14145. var faceDataArrays = callback(data);
  14146. if (!faceDataArrays) {
  14147. return;
  14148. }
  14149. if (mipmmapGenerator) {
  14150. var textureType = _this._getWebGLTextureType(type);
  14151. var internalFormat = _this._getInternalFormat(format);
  14152. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14153. var needConversion = false;
  14154. if (internalFormat === gl.RGB) {
  14155. internalFormat = gl.RGBA;
  14156. needConversion = true;
  14157. }
  14158. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14159. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14160. var mipData = mipmmapGenerator(faceDataArrays);
  14161. for (var level = 0; level < mipData.length; level++) {
  14162. var mipSize = width >> level;
  14163. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14164. var mipFaceData = mipData[level][faceIndex];
  14165. if (needConversion) {
  14166. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14167. }
  14168. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14169. }
  14170. }
  14171. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14172. }
  14173. else {
  14174. texture.generateMipMaps = !noMipmap;
  14175. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14176. }
  14177. texture.isReady = true;
  14178. // this.resetTextureCache();
  14179. scene._removePendingData(texture);
  14180. if (onLoad) {
  14181. onLoad();
  14182. }
  14183. };
  14184. this._loadFile(url, function (data) {
  14185. internalCallback(data);
  14186. }, undefined, scene.database, true, onerror);
  14187. return texture;
  14188. };
  14189. ;
  14190. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14191. if (compression === void 0) { compression = null; }
  14192. var internalFormat = this._getInternalFormat(format);
  14193. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14194. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14195. if (!this._doNotHandleContextLost) {
  14196. texture._bufferView = data;
  14197. texture.format = format;
  14198. texture.invertY = invertY;
  14199. texture._compression = compression;
  14200. }
  14201. if (texture.width % 4 !== 0) {
  14202. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14203. }
  14204. if (compression && data) {
  14205. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14206. }
  14207. else {
  14208. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14209. }
  14210. if (texture.generateMipMaps) {
  14211. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14212. }
  14213. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14214. // this.resetTextureCache();
  14215. texture.isReady = true;
  14216. };
  14217. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14218. if (compression === void 0) { compression = null; }
  14219. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14220. texture.baseWidth = width;
  14221. texture.baseHeight = height;
  14222. texture.baseDepth = depth;
  14223. texture.width = width;
  14224. texture.height = height;
  14225. texture.depth = depth;
  14226. texture.format = format;
  14227. texture.generateMipMaps = generateMipMaps;
  14228. texture.samplingMode = samplingMode;
  14229. texture.is3D = true;
  14230. if (!this._doNotHandleContextLost) {
  14231. texture._bufferView = data;
  14232. }
  14233. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14234. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14235. // Filters
  14236. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14237. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14238. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14239. if (generateMipMaps) {
  14240. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14241. }
  14242. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14243. this._internalTexturesCache.push(texture);
  14244. return texture;
  14245. };
  14246. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14247. var gl = this._gl;
  14248. if (!gl) {
  14249. return;
  14250. }
  14251. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14254. if (!noMipmap && !isCompressed) {
  14255. gl.generateMipmap(gl.TEXTURE_2D);
  14256. }
  14257. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14258. // this.resetTextureCache();
  14259. if (scene) {
  14260. scene._removePendingData(texture);
  14261. }
  14262. texture.onLoadedObservable.notifyObservers(texture);
  14263. texture.onLoadedObservable.clear();
  14264. };
  14265. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14266. var _this = this;
  14267. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14268. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14269. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14270. var gl = this._gl;
  14271. if (!gl) {
  14272. return;
  14273. }
  14274. if (!texture._webGLTexture) {
  14275. // this.resetTextureCache();
  14276. if (scene) {
  14277. scene._removePendingData(texture);
  14278. }
  14279. return;
  14280. }
  14281. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14282. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14283. texture.baseWidth = width;
  14284. texture.baseHeight = height;
  14285. texture.width = potWidth;
  14286. texture.height = potHeight;
  14287. texture.isReady = true;
  14288. if (processFunction(potWidth, potHeight, function () {
  14289. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14290. })) {
  14291. // Returning as texture needs extra async steps
  14292. return;
  14293. }
  14294. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14295. };
  14296. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14297. // Create new RGBA data container.
  14298. var rgbaData;
  14299. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14300. rgbaData = new Float32Array(width * height * 4);
  14301. }
  14302. else {
  14303. rgbaData = new Uint32Array(width * height * 4);
  14304. }
  14305. // Convert each pixel.
  14306. for (var x = 0; x < width; x++) {
  14307. for (var y = 0; y < height; y++) {
  14308. var index = (y * width + x) * 3;
  14309. var newIndex = (y * width + x) * 4;
  14310. // Map Old Value to new value.
  14311. rgbaData[newIndex + 0] = rgbData[index + 0];
  14312. rgbaData[newIndex + 1] = rgbData[index + 1];
  14313. rgbaData[newIndex + 2] = rgbData[index + 2];
  14314. // Add fully opaque alpha channel.
  14315. rgbaData[newIndex + 3] = 1;
  14316. }
  14317. }
  14318. return rgbaData;
  14319. };
  14320. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14321. var gl = this._gl;
  14322. if (texture._framebuffer) {
  14323. gl.deleteFramebuffer(texture._framebuffer);
  14324. texture._framebuffer = null;
  14325. }
  14326. if (texture._depthStencilBuffer) {
  14327. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14328. texture._depthStencilBuffer = null;
  14329. }
  14330. if (texture._MSAAFramebuffer) {
  14331. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14332. texture._MSAAFramebuffer = null;
  14333. }
  14334. if (texture._MSAARenderBuffer) {
  14335. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14336. texture._MSAARenderBuffer = null;
  14337. }
  14338. };
  14339. Engine.prototype._releaseTexture = function (texture) {
  14340. var gl = this._gl;
  14341. this._releaseFramebufferObjects(texture);
  14342. gl.deleteTexture(texture._webGLTexture);
  14343. // Unbind channels
  14344. this.unbindAllTextures();
  14345. var index = this._internalTexturesCache.indexOf(texture);
  14346. if (index !== -1) {
  14347. this._internalTexturesCache.splice(index, 1);
  14348. }
  14349. // Integrated fixed lod samplers.
  14350. if (texture._lodTextureHigh) {
  14351. texture._lodTextureHigh.dispose();
  14352. }
  14353. if (texture._lodTextureMid) {
  14354. texture._lodTextureMid.dispose();
  14355. }
  14356. if (texture._lodTextureLow) {
  14357. texture._lodTextureLow.dispose();
  14358. }
  14359. };
  14360. Engine.prototype.setProgram = function (program) {
  14361. if (this._currentProgram !== program) {
  14362. this._gl.useProgram(program);
  14363. this._currentProgram = program;
  14364. }
  14365. };
  14366. Engine.prototype.bindSamplers = function (effect) {
  14367. this.setProgram(effect.getProgram());
  14368. var samplers = effect.getSamplers();
  14369. for (var index = 0; index < samplers.length; index++) {
  14370. var uniform = effect.getUniform(samplers[index]);
  14371. if (uniform) {
  14372. this._boundUniforms[index] = uniform;
  14373. }
  14374. }
  14375. this._currentEffect = null;
  14376. };
  14377. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14378. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14379. return;
  14380. }
  14381. // Remove
  14382. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14383. // Bind last to it
  14384. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14385. // Bind to dummy
  14386. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14387. };
  14388. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14389. if (!internalTexture) {
  14390. return -1;
  14391. }
  14392. internalTexture._initialSlot = channel;
  14393. if (this.disableTextureBindingOptimization) {
  14394. if (channel !== internalTexture._designatedSlot) {
  14395. this._textureCollisions.addCount(1, false);
  14396. }
  14397. }
  14398. else {
  14399. if (channel !== internalTexture._designatedSlot) {
  14400. if (internalTexture._designatedSlot > -1) {
  14401. return internalTexture._designatedSlot;
  14402. }
  14403. else {
  14404. // No slot for this texture, let's pick a new one (if we find a free slot)
  14405. if (this._nextFreeTextureSlots.length) {
  14406. return this._nextFreeTextureSlots[0];
  14407. }
  14408. // We need to recycle the oldest bound texture, sorry.
  14409. this._textureCollisions.addCount(1, false);
  14410. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14411. }
  14412. }
  14413. }
  14414. return channel;
  14415. };
  14416. Engine.prototype._linkTrackers = function (previous, next) {
  14417. previous.next = next;
  14418. next.previous = previous;
  14419. };
  14420. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14421. var currentSlot = internalTexture._designatedSlot;
  14422. if (currentSlot === -1) {
  14423. return -1;
  14424. }
  14425. internalTexture._designatedSlot = -1;
  14426. if (this.disableTextureBindingOptimization) {
  14427. return -1;
  14428. }
  14429. // Remove from bound list
  14430. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14431. // Free the slot
  14432. this._boundTexturesCache[currentSlot] = null;
  14433. this._nextFreeTextureSlots.push(currentSlot);
  14434. return currentSlot;
  14435. };
  14436. Engine.prototype._activateCurrentTexture = function () {
  14437. if (this._currentTextureChannel !== this._activeChannel) {
  14438. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14439. this._currentTextureChannel = this._activeChannel;
  14440. }
  14441. };
  14442. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14443. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14444. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14445. this._activeChannel = texture._designatedSlot;
  14446. }
  14447. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14448. var isTextureForRendering = texture && texture._initialSlot > -1;
  14449. if (currentTextureBound !== texture) {
  14450. if (currentTextureBound) {
  14451. this._removeDesignatedSlot(currentTextureBound);
  14452. }
  14453. this._activateCurrentTexture();
  14454. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14455. this._boundTexturesCache[this._activeChannel] = texture;
  14456. if (texture) {
  14457. if (!this.disableTextureBindingOptimization) {
  14458. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14459. if (slotIndex > -1) {
  14460. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14461. }
  14462. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14463. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14464. }
  14465. texture._designatedSlot = this._activeChannel;
  14466. }
  14467. }
  14468. else if (forTextureDataUpdate) {
  14469. this._activateCurrentTexture();
  14470. }
  14471. if (isTextureForRendering && !forTextureDataUpdate) {
  14472. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14473. }
  14474. };
  14475. Engine.prototype._bindTexture = function (channel, texture) {
  14476. if (channel < 0) {
  14477. return;
  14478. }
  14479. if (texture) {
  14480. channel = this._getCorrectTextureChannel(channel, texture);
  14481. }
  14482. this._activeChannel = channel;
  14483. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14484. };
  14485. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14486. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14487. };
  14488. Engine.prototype.unbindAllTextures = function () {
  14489. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14490. this._activeChannel = channel;
  14491. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14492. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14493. if (this.webGLVersion > 1) {
  14494. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14495. }
  14496. }
  14497. };
  14498. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14499. if (channel < 0) {
  14500. return;
  14501. }
  14502. if (uniform) {
  14503. this._boundUniforms[channel] = uniform;
  14504. }
  14505. this._setTexture(channel, texture);
  14506. };
  14507. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14508. var uniform = this._boundUniforms[sourceSlot];
  14509. if (uniform._currentState === destination) {
  14510. return;
  14511. }
  14512. this._gl.uniform1i(uniform, destination);
  14513. uniform._currentState = destination;
  14514. };
  14515. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14516. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14517. // Not ready?
  14518. if (!texture) {
  14519. if (this._boundTexturesCache[channel] != null) {
  14520. this._activeChannel = channel;
  14521. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14522. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14523. if (this.webGLVersion > 1) {
  14524. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14525. }
  14526. }
  14527. return false;
  14528. }
  14529. // Video
  14530. if (texture.video) {
  14531. this._activeChannel = channel;
  14532. texture.update();
  14533. }
  14534. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14535. texture.delayLoad();
  14536. return false;
  14537. }
  14538. var internalTexture;
  14539. if (texture.isReady()) {
  14540. internalTexture = texture.getInternalTexture();
  14541. }
  14542. else if (texture.isCube) {
  14543. internalTexture = this.emptyCubeTexture;
  14544. }
  14545. else if (texture.is3D) {
  14546. internalTexture = this.emptyTexture3D;
  14547. }
  14548. else {
  14549. internalTexture = this.emptyTexture;
  14550. }
  14551. if (!isPartOfTextureArray) {
  14552. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14553. }
  14554. if (this._boundTexturesCache[channel] === internalTexture) {
  14555. this._moveBoundTextureOnTop(internalTexture);
  14556. if (!isPartOfTextureArray) {
  14557. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14558. }
  14559. return false;
  14560. }
  14561. this._activeChannel = channel;
  14562. if (internalTexture && internalTexture.is3D) {
  14563. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14564. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14565. internalTexture._cachedWrapU = texture.wrapU;
  14566. switch (texture.wrapU) {
  14567. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14568. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14569. break;
  14570. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14571. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14572. break;
  14573. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14574. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14575. break;
  14576. }
  14577. }
  14578. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14579. internalTexture._cachedWrapV = texture.wrapV;
  14580. switch (texture.wrapV) {
  14581. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14582. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14583. break;
  14584. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14585. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14586. break;
  14587. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14588. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14589. break;
  14590. }
  14591. }
  14592. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14593. internalTexture._cachedWrapR = texture.wrapR;
  14594. switch (texture.wrapR) {
  14595. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14596. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14597. break;
  14598. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14599. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14600. break;
  14601. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14602. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14603. break;
  14604. }
  14605. }
  14606. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14607. }
  14608. else if (internalTexture && internalTexture.isCube) {
  14609. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14610. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14611. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14612. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14613. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14614. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14615. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14616. }
  14617. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14618. }
  14619. else {
  14620. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14621. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14622. internalTexture._cachedWrapU = texture.wrapU;
  14623. switch (texture.wrapU) {
  14624. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14626. break;
  14627. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14628. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14629. break;
  14630. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14631. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14632. break;
  14633. }
  14634. }
  14635. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14636. internalTexture._cachedWrapV = texture.wrapV;
  14637. switch (texture.wrapV) {
  14638. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14639. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14640. break;
  14641. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14642. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14643. break;
  14644. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14645. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14646. break;
  14647. }
  14648. }
  14649. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14650. }
  14651. return true;
  14652. };
  14653. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14654. if (channel < 0 || !uniform) {
  14655. return;
  14656. }
  14657. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14658. this._textureUnits = new Int32Array(textures.length);
  14659. }
  14660. for (var i = 0; i < textures.length; i++) {
  14661. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14662. }
  14663. this._gl.uniform1iv(uniform, this._textureUnits);
  14664. for (var index = 0; index < textures.length; index++) {
  14665. this._setTexture(this._textureUnits[index], textures[index], true);
  14666. }
  14667. };
  14668. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14669. var internalTexture = texture.getInternalTexture();
  14670. if (!internalTexture) {
  14671. return;
  14672. }
  14673. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14674. var value = texture.anisotropicFilteringLevel;
  14675. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14676. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14677. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14678. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14679. }
  14680. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14681. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14682. internalTexture._cachedAnisotropicFilteringLevel = value;
  14683. }
  14684. };
  14685. Engine.prototype.readPixels = function (x, y, width, height) {
  14686. var data = new Uint8Array(height * width * 4);
  14687. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14688. return data;
  14689. };
  14690. /**
  14691. * Add an externaly attached data from its key.
  14692. * This method call will fail and return false, if such key already exists.
  14693. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14694. * @param key the unique key that identifies the data
  14695. * @param data the data object to associate to the key for this Engine instance
  14696. * @return true if no such key were already present and the data was added successfully, false otherwise
  14697. */
  14698. Engine.prototype.addExternalData = function (key, data) {
  14699. if (!this._externalData) {
  14700. this._externalData = new BABYLON.StringDictionary();
  14701. }
  14702. return this._externalData.add(key, data);
  14703. };
  14704. /**
  14705. * Get an externaly attached data from its key
  14706. * @param key the unique key that identifies the data
  14707. * @return the associated data, if present (can be null), or undefined if not present
  14708. */
  14709. Engine.prototype.getExternalData = function (key) {
  14710. if (!this._externalData) {
  14711. this._externalData = new BABYLON.StringDictionary();
  14712. }
  14713. return this._externalData.get(key);
  14714. };
  14715. /**
  14716. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14717. * @param key the unique key that identifies the data
  14718. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14719. * @return the associated data, can be null if the factory returned null.
  14720. */
  14721. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14722. if (!this._externalData) {
  14723. this._externalData = new BABYLON.StringDictionary();
  14724. }
  14725. return this._externalData.getOrAddWithFactory(key, factory);
  14726. };
  14727. /**
  14728. * Remove an externaly attached data from the Engine instance
  14729. * @param key the unique key that identifies the data
  14730. * @return true if the data was successfully removed, false if it doesn't exist
  14731. */
  14732. Engine.prototype.removeExternalData = function (key) {
  14733. if (!this._externalData) {
  14734. this._externalData = new BABYLON.StringDictionary();
  14735. }
  14736. return this._externalData.remove(key);
  14737. };
  14738. Engine.prototype.unbindAllAttributes = function () {
  14739. if (this._mustWipeVertexAttributes) {
  14740. this._mustWipeVertexAttributes = false;
  14741. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14742. this._gl.disableVertexAttribArray(i);
  14743. this._vertexAttribArraysEnabled[i] = false;
  14744. this._currentBufferPointers[i].active = false;
  14745. }
  14746. return;
  14747. }
  14748. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14749. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14750. continue;
  14751. }
  14752. this._gl.disableVertexAttribArray(i);
  14753. this._vertexAttribArraysEnabled[i] = false;
  14754. this._currentBufferPointers[i].active = false;
  14755. }
  14756. };
  14757. Engine.prototype.releaseEffects = function () {
  14758. for (var name in this._compiledEffects) {
  14759. this._deleteProgram(this._compiledEffects[name]._program);
  14760. }
  14761. this._compiledEffects = {};
  14762. };
  14763. // Dispose
  14764. Engine.prototype.dispose = function () {
  14765. this.hideLoadingUI();
  14766. this.stopRenderLoop();
  14767. // Release postProcesses
  14768. while (this.postProcesses.length) {
  14769. this.postProcesses[0].dispose();
  14770. }
  14771. // Empty texture
  14772. if (this._emptyTexture) {
  14773. this._releaseTexture(this._emptyTexture);
  14774. this._emptyTexture = null;
  14775. }
  14776. if (this._emptyCubeTexture) {
  14777. this._releaseTexture(this._emptyCubeTexture);
  14778. this._emptyCubeTexture = null;
  14779. }
  14780. // Rescale PP
  14781. if (this._rescalePostProcess) {
  14782. this._rescalePostProcess.dispose();
  14783. }
  14784. // Release scenes
  14785. while (this.scenes.length) {
  14786. this.scenes[0].dispose();
  14787. }
  14788. // Release audio engine
  14789. if (Engine.audioEngine) {
  14790. Engine.audioEngine.dispose();
  14791. }
  14792. // Release effects
  14793. this.releaseEffects();
  14794. // Unbind
  14795. this.unbindAllAttributes();
  14796. if (this._dummyFramebuffer) {
  14797. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14798. }
  14799. //WebVR
  14800. this.disableVR();
  14801. // Events
  14802. if (BABYLON.Tools.IsWindowObjectExist()) {
  14803. window.removeEventListener("blur", this._onBlur);
  14804. window.removeEventListener("focus", this._onFocus);
  14805. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14806. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14807. if (this._renderingCanvas) {
  14808. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14809. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14810. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14811. if (!this._doNotHandleContextLost) {
  14812. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14813. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14814. }
  14815. }
  14816. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14817. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14818. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14819. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14820. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14821. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14822. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14823. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14824. if (this._onVrDisplayConnect) {
  14825. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14826. if (this._onVrDisplayDisconnect) {
  14827. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14828. }
  14829. if (this._onVrDisplayPresentChange) {
  14830. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14831. }
  14832. this._onVrDisplayConnect = null;
  14833. this._onVrDisplayDisconnect = null;
  14834. }
  14835. }
  14836. // Remove from Instances
  14837. var index = Engine.Instances.indexOf(this);
  14838. if (index >= 0) {
  14839. Engine.Instances.splice(index, 1);
  14840. }
  14841. this._workingCanvas = null;
  14842. this._workingContext = null;
  14843. this._currentBufferPointers = [];
  14844. this._renderingCanvas = null;
  14845. this._currentProgram = null;
  14846. this.onResizeObservable.clear();
  14847. this.onCanvasBlurObservable.clear();
  14848. this.onCanvasFocusObservable.clear();
  14849. this.onCanvasPointerOutObservable.clear();
  14850. this.onBeginFrameObservable.clear();
  14851. this.onEndFrameObservable.clear();
  14852. BABYLON.Effect.ResetCache();
  14853. // Abort active requests
  14854. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14855. var request = _a[_i];
  14856. request.abort();
  14857. }
  14858. };
  14859. // Loading screen
  14860. Engine.prototype.displayLoadingUI = function () {
  14861. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14862. return;
  14863. }
  14864. var loadingScreen = this.loadingScreen;
  14865. if (loadingScreen) {
  14866. loadingScreen.displayLoadingUI();
  14867. }
  14868. };
  14869. Engine.prototype.hideLoadingUI = function () {
  14870. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14871. return;
  14872. }
  14873. var loadingScreen = this.loadingScreen;
  14874. if (loadingScreen) {
  14875. loadingScreen.hideLoadingUI();
  14876. }
  14877. };
  14878. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14879. get: function () {
  14880. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14881. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14882. return this._loadingScreen;
  14883. },
  14884. set: function (loadingScreen) {
  14885. this._loadingScreen = loadingScreen;
  14886. },
  14887. enumerable: true,
  14888. configurable: true
  14889. });
  14890. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14891. set: function (text) {
  14892. this.loadingScreen.loadingUIText = text;
  14893. },
  14894. enumerable: true,
  14895. configurable: true
  14896. });
  14897. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14898. set: function (color) {
  14899. this.loadingScreen.loadingUIBackgroundColor = color;
  14900. },
  14901. enumerable: true,
  14902. configurable: true
  14903. });
  14904. Engine.prototype.attachContextLostEvent = function (callback) {
  14905. if (this._renderingCanvas) {
  14906. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14907. }
  14908. };
  14909. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14910. if (this._renderingCanvas) {
  14911. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14912. }
  14913. };
  14914. Engine.prototype.getVertexShaderSource = function (program) {
  14915. var shaders = this._gl.getAttachedShaders(program);
  14916. if (!shaders) {
  14917. return null;
  14918. }
  14919. return this._gl.getShaderSource(shaders[0]);
  14920. };
  14921. Engine.prototype.getFragmentShaderSource = function (program) {
  14922. var shaders = this._gl.getAttachedShaders(program);
  14923. if (!shaders) {
  14924. return null;
  14925. }
  14926. return this._gl.getShaderSource(shaders[1]);
  14927. };
  14928. Engine.prototype.getError = function () {
  14929. return this._gl.getError();
  14930. };
  14931. // FPS
  14932. Engine.prototype.getFps = function () {
  14933. return this._fps;
  14934. };
  14935. Engine.prototype.getDeltaTime = function () {
  14936. return this._deltaTime;
  14937. };
  14938. Engine.prototype._measureFps = function () {
  14939. this._performanceMonitor.sampleFrame();
  14940. this._fps = this._performanceMonitor.averageFPS;
  14941. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14942. };
  14943. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14944. if (faceIndex === void 0) { faceIndex = -1; }
  14945. var gl = this._gl;
  14946. if (!this._dummyFramebuffer) {
  14947. var dummy = gl.createFramebuffer();
  14948. if (!dummy) {
  14949. throw new Error("Unable to create dummy framebuffer");
  14950. }
  14951. this._dummyFramebuffer = dummy;
  14952. }
  14953. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14954. if (faceIndex > -1) {
  14955. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14956. }
  14957. else {
  14958. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14959. }
  14960. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14961. var buffer;
  14962. switch (readType) {
  14963. case gl.UNSIGNED_BYTE:
  14964. buffer = new Uint8Array(4 * width * height);
  14965. readType = gl.UNSIGNED_BYTE;
  14966. break;
  14967. default:
  14968. buffer = new Float32Array(4 * width * height);
  14969. readType = gl.FLOAT;
  14970. break;
  14971. }
  14972. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14973. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14974. return buffer;
  14975. };
  14976. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14977. if (this._webGLVersion > 1) {
  14978. return this._caps.colorBufferFloat;
  14979. }
  14980. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14981. };
  14982. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14983. if (this._webGLVersion > 1) {
  14984. return this._caps.colorBufferFloat;
  14985. }
  14986. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14987. };
  14988. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14989. Engine.prototype._canRenderToFramebuffer = function (type) {
  14990. var gl = this._gl;
  14991. //clear existing errors
  14992. while (gl.getError() !== gl.NO_ERROR) { }
  14993. var successful = true;
  14994. var texture = gl.createTexture();
  14995. gl.bindTexture(gl.TEXTURE_2D, texture);
  14996. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14999. var fb = gl.createFramebuffer();
  15000. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15002. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15003. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15004. successful = successful && (gl.getError() === gl.NO_ERROR);
  15005. //try render by clearing frame buffer's color buffer
  15006. if (successful) {
  15007. gl.clear(gl.COLOR_BUFFER_BIT);
  15008. successful = successful && (gl.getError() === gl.NO_ERROR);
  15009. }
  15010. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15011. if (successful) {
  15012. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15013. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15014. var readFormat = gl.RGBA;
  15015. var readType = gl.UNSIGNED_BYTE;
  15016. var buffer = new Uint8Array(4);
  15017. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15018. successful = successful && (gl.getError() === gl.NO_ERROR);
  15019. }
  15020. //clean up
  15021. gl.deleteTexture(texture);
  15022. gl.deleteFramebuffer(fb);
  15023. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15024. //clear accumulated errors
  15025. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15026. return successful;
  15027. };
  15028. Engine.prototype._getWebGLTextureType = function (type) {
  15029. if (type === Engine.TEXTURETYPE_FLOAT) {
  15030. return this._gl.FLOAT;
  15031. }
  15032. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15033. // Add Half Float Constant.
  15034. return this._gl.HALF_FLOAT_OES;
  15035. }
  15036. return this._gl.UNSIGNED_BYTE;
  15037. };
  15038. ;
  15039. /** @ignore */
  15040. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15041. if (this._webGLVersion === 1) {
  15042. return this._gl.RGBA;
  15043. }
  15044. if (type === Engine.TEXTURETYPE_FLOAT) {
  15045. if (format) {
  15046. switch (format) {
  15047. case Engine.TEXTUREFORMAT_R32F:
  15048. return this._gl.R32F;
  15049. case Engine.TEXTUREFORMAT_RG32F:
  15050. return this._gl.RG32F;
  15051. case Engine.TEXTUREFORMAT_RGB32F:
  15052. return this._gl.RGB32F;
  15053. }
  15054. }
  15055. return this._gl.RGBA32F;
  15056. }
  15057. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15058. return this._gl.RGBA16F;
  15059. }
  15060. return this._gl.RGBA;
  15061. };
  15062. ;
  15063. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15064. if (type === Engine.TEXTURETYPE_FLOAT) {
  15065. return this._gl.RGBA32F;
  15066. }
  15067. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15068. return this._gl.RGBA16F;
  15069. }
  15070. return this._gl.RGBA8;
  15071. };
  15072. ;
  15073. Engine.prototype.createQuery = function () {
  15074. return this._gl.createQuery();
  15075. };
  15076. Engine.prototype.deleteQuery = function (query) {
  15077. this._gl.deleteQuery(query);
  15078. return this;
  15079. };
  15080. Engine.prototype.isQueryResultAvailable = function (query) {
  15081. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15082. };
  15083. Engine.prototype.getQueryResult = function (query) {
  15084. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15085. };
  15086. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15087. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15088. this._gl.beginQuery(glAlgorithm, query);
  15089. return this;
  15090. };
  15091. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15092. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15093. this._gl.endQuery(glAlgorithm);
  15094. return this;
  15095. };
  15096. /* Time queries */
  15097. Engine.prototype._createTimeQuery = function () {
  15098. var timerQuery = this._caps.timerQuery;
  15099. if (timerQuery.createQueryEXT) {
  15100. return timerQuery.createQueryEXT();
  15101. }
  15102. return this.createQuery();
  15103. };
  15104. Engine.prototype._deleteTimeQuery = function (query) {
  15105. var timerQuery = this._caps.timerQuery;
  15106. if (timerQuery.deleteQueryEXT) {
  15107. timerQuery.deleteQueryEXT(query);
  15108. return;
  15109. }
  15110. this.deleteQuery(query);
  15111. };
  15112. Engine.prototype._getTimeQueryResult = function (query) {
  15113. var timerQuery = this._caps.timerQuery;
  15114. if (timerQuery.getQueryObjectEXT) {
  15115. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15116. }
  15117. return this.getQueryResult(query);
  15118. };
  15119. Engine.prototype._getTimeQueryAvailability = function (query) {
  15120. var timerQuery = this._caps.timerQuery;
  15121. if (timerQuery.getQueryObjectEXT) {
  15122. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15123. }
  15124. return this.isQueryResultAvailable(query);
  15125. };
  15126. Engine.prototype.startTimeQuery = function () {
  15127. var timerQuery = this._caps.timerQuery;
  15128. if (!timerQuery) {
  15129. return null;
  15130. }
  15131. var token = new BABYLON._TimeToken();
  15132. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15133. if (this._caps.canUseTimestampForTimerQuery) {
  15134. token._startTimeQuery = this._createTimeQuery();
  15135. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15136. }
  15137. else {
  15138. if (this._currentNonTimestampToken) {
  15139. return this._currentNonTimestampToken;
  15140. }
  15141. token._timeElapsedQuery = this._createTimeQuery();
  15142. if (timerQuery.beginQueryEXT) {
  15143. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15144. }
  15145. else {
  15146. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15147. }
  15148. this._currentNonTimestampToken = token;
  15149. }
  15150. return token;
  15151. };
  15152. Engine.prototype.endTimeQuery = function (token) {
  15153. var timerQuery = this._caps.timerQuery;
  15154. if (!timerQuery || !token) {
  15155. return -1;
  15156. }
  15157. if (this._caps.canUseTimestampForTimerQuery) {
  15158. if (!token._startTimeQuery) {
  15159. return -1;
  15160. }
  15161. if (!token._endTimeQuery) {
  15162. token._endTimeQuery = this._createTimeQuery();
  15163. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15164. }
  15165. }
  15166. else if (!token._timeElapsedQueryEnded) {
  15167. if (!token._timeElapsedQuery) {
  15168. return -1;
  15169. }
  15170. if (timerQuery.endQueryEXT) {
  15171. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15172. }
  15173. else {
  15174. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15175. }
  15176. token._timeElapsedQueryEnded = true;
  15177. }
  15178. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15179. var available = false;
  15180. if (token._endTimeQuery) {
  15181. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15182. }
  15183. else if (token._timeElapsedQuery) {
  15184. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15185. }
  15186. if (available && !disjoint) {
  15187. var result = 0;
  15188. if (this._caps.canUseTimestampForTimerQuery) {
  15189. if (!token._startTimeQuery || !token._endTimeQuery) {
  15190. return -1;
  15191. }
  15192. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15193. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15194. result = timeEnd - timeStart;
  15195. this._deleteTimeQuery(token._startTimeQuery);
  15196. this._deleteTimeQuery(token._endTimeQuery);
  15197. token._startTimeQuery = null;
  15198. token._endTimeQuery = null;
  15199. }
  15200. else {
  15201. if (!token._timeElapsedQuery) {
  15202. return -1;
  15203. }
  15204. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15205. this._deleteTimeQuery(token._timeElapsedQuery);
  15206. token._timeElapsedQuery = null;
  15207. token._timeElapsedQueryEnded = false;
  15208. this._currentNonTimestampToken = null;
  15209. }
  15210. return result;
  15211. }
  15212. return -1;
  15213. };
  15214. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15215. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15216. };
  15217. // Transform feedback
  15218. Engine.prototype.createTransformFeedback = function () {
  15219. return this._gl.createTransformFeedback();
  15220. };
  15221. Engine.prototype.deleteTransformFeedback = function (value) {
  15222. this._gl.deleteTransformFeedback(value);
  15223. };
  15224. Engine.prototype.bindTransformFeedback = function (value) {
  15225. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15226. };
  15227. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15228. if (usePoints === void 0) { usePoints = true; }
  15229. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15230. };
  15231. Engine.prototype.endTransformFeedback = function () {
  15232. this._gl.endTransformFeedback();
  15233. };
  15234. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15235. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15236. };
  15237. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15238. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15239. };
  15240. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15241. var _this = this;
  15242. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15243. this._activeRequests.push(request);
  15244. request.onCompleteObservable.add(function (request) {
  15245. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15246. });
  15247. return request;
  15248. };
  15249. /** @ignore */
  15250. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15251. var _this = this;
  15252. return new Promise(function (resolve, reject) {
  15253. _this._loadFile(url, function (data) {
  15254. resolve(data);
  15255. }, undefined, database, useArrayBuffer, function (request, exception) {
  15256. reject(exception);
  15257. });
  15258. });
  15259. };
  15260. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15261. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15262. var onload = function (data) {
  15263. loadedFiles[index] = data;
  15264. loadedFiles._internalCount++;
  15265. if (loadedFiles._internalCount === 6) {
  15266. onfinish(loadedFiles);
  15267. }
  15268. };
  15269. var onerror = function (request, exception) {
  15270. if (onErrorCallBack && request) {
  15271. onErrorCallBack(request.status + " " + request.statusText, exception);
  15272. }
  15273. };
  15274. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15275. };
  15276. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15277. if (onError === void 0) { onError = null; }
  15278. var loadedFiles = [];
  15279. loadedFiles._internalCount = 0;
  15280. for (var index = 0; index < 6; index++) {
  15281. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15282. }
  15283. };
  15284. // Statics
  15285. Engine.isSupported = function () {
  15286. try {
  15287. var tempcanvas = document.createElement("canvas");
  15288. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15289. return gl != null && !!window.WebGLRenderingContext;
  15290. }
  15291. catch (e) {
  15292. return false;
  15293. }
  15294. };
  15295. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15296. Engine.ExceptionList = [
  15297. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15298. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15299. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15300. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15301. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15302. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15303. ];
  15304. Engine.Instances = new Array();
  15305. // Const statics
  15306. Engine._ALPHA_DISABLE = 0;
  15307. Engine._ALPHA_ADD = 1;
  15308. Engine._ALPHA_COMBINE = 2;
  15309. Engine._ALPHA_SUBTRACT = 3;
  15310. Engine._ALPHA_MULTIPLY = 4;
  15311. Engine._ALPHA_MAXIMIZED = 5;
  15312. Engine._ALPHA_ONEONE = 6;
  15313. Engine._ALPHA_PREMULTIPLIED = 7;
  15314. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15315. Engine._ALPHA_INTERPOLATE = 9;
  15316. Engine._ALPHA_SCREENMODE = 10;
  15317. Engine._DELAYLOADSTATE_NONE = 0;
  15318. Engine._DELAYLOADSTATE_LOADED = 1;
  15319. Engine._DELAYLOADSTATE_LOADING = 2;
  15320. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15321. Engine._TEXTUREFORMAT_ALPHA = 0;
  15322. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15323. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15324. Engine._TEXTUREFORMAT_RGB = 4;
  15325. Engine._TEXTUREFORMAT_RGBA = 5;
  15326. Engine._TEXTUREFORMAT_R32F = 6;
  15327. Engine._TEXTUREFORMAT_RG32F = 7;
  15328. Engine._TEXTUREFORMAT_RGB32F = 8;
  15329. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15330. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15331. Engine._TEXTURETYPE_FLOAT = 1;
  15332. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15333. // Depht or Stencil test Constants.
  15334. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15335. 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.
  15336. 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.
  15337. 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.
  15338. 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.
  15339. 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.
  15340. 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.
  15341. 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.
  15342. // Stencil Actions Constants.
  15343. Engine._KEEP = 0x1E00;
  15344. Engine._REPLACE = 0x1E01;
  15345. Engine._INCR = 0x1E02;
  15346. Engine._DECR = 0x1E03;
  15347. Engine._INVERT = 0x150A;
  15348. Engine._INCR_WRAP = 0x8507;
  15349. Engine._DECR_WRAP = 0x8508;
  15350. // Texture rescaling mode
  15351. Engine._SCALEMODE_FLOOR = 1;
  15352. Engine._SCALEMODE_NEAREST = 2;
  15353. Engine._SCALEMODE_CEILING = 3;
  15354. // Updatable statics so stick with vars here
  15355. Engine.CollisionsEpsilon = 0.001;
  15356. Engine.CodeRepository = "src/";
  15357. Engine.ShadersRepository = "src/Shaders/";
  15358. return Engine;
  15359. }());
  15360. BABYLON.Engine = Engine;
  15361. })(BABYLON || (BABYLON = {}));
  15362. //# sourceMappingURL=babylon.engine.js.map
  15363. var BABYLON;
  15364. (function (BABYLON) {
  15365. /**
  15366. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15367. */
  15368. var Node = /** @class */ (function () {
  15369. /**
  15370. * Creates a new Node
  15371. * @param {string} name - the name and id to be given to this node
  15372. * @param {BABYLON.Scene} the scene this node will be added to
  15373. */
  15374. function Node(name, scene) {
  15375. if (scene === void 0) { scene = null; }
  15376. /**
  15377. * Gets or sets a string used to store user defined state for the node
  15378. */
  15379. this.state = "";
  15380. /**
  15381. * Gets or sets an object used to store user defined information for the node
  15382. */
  15383. this.metadata = null;
  15384. /**
  15385. * Gets or sets a boolean used to define if the node must be serialized
  15386. */
  15387. this.doNotSerialize = false;
  15388. /** @ignore */
  15389. this._isDisposed = false;
  15390. /**
  15391. * Gets a list of {BABYLON.Animation} associated with the node
  15392. */
  15393. this.animations = new Array();
  15394. this._ranges = {};
  15395. this._isEnabled = true;
  15396. this._isReady = true;
  15397. /** @ignore */
  15398. this._currentRenderId = -1;
  15399. this._parentRenderId = -1;
  15400. this._animationPropertiesOverride = null;
  15401. /**
  15402. * An event triggered when the mesh is disposed
  15403. * @type {BABYLON.Observable}
  15404. */
  15405. this.onDisposeObservable = new BABYLON.Observable();
  15406. // Behaviors
  15407. this._behaviors = new Array();
  15408. this.name = name;
  15409. this.id = name;
  15410. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15411. this.uniqueId = this._scene.getUniqueId();
  15412. this._initCache();
  15413. }
  15414. /**
  15415. * Gets a boolean indicating if the node has been disposed
  15416. * @returns true if the node was disposed
  15417. */
  15418. Node.prototype.isDisposed = function () {
  15419. return this._isDisposed;
  15420. };
  15421. Object.defineProperty(Node.prototype, "parent", {
  15422. get: function () {
  15423. return this._parentNode;
  15424. },
  15425. /**
  15426. * Gets or sets the parent of the node
  15427. */
  15428. set: function (parent) {
  15429. if (this._parentNode === parent) {
  15430. return;
  15431. }
  15432. // Remove self from list of children of parent
  15433. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15434. var index = this._parentNode._children.indexOf(this);
  15435. if (index !== -1) {
  15436. this._parentNode._children.splice(index, 1);
  15437. }
  15438. }
  15439. // Store new parent
  15440. this._parentNode = parent;
  15441. // Add as child to new parent
  15442. if (this._parentNode) {
  15443. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15444. this._parentNode._children = new Array();
  15445. }
  15446. this._parentNode._children.push(this);
  15447. }
  15448. },
  15449. enumerable: true,
  15450. configurable: true
  15451. });
  15452. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15453. /**
  15454. * Gets or sets the animation properties override
  15455. */
  15456. get: function () {
  15457. return this._animationPropertiesOverride;
  15458. },
  15459. set: function (value) {
  15460. this._animationPropertiesOverride = value;
  15461. },
  15462. enumerable: true,
  15463. configurable: true
  15464. });
  15465. /**
  15466. * Gets a string idenfifying the name of the class
  15467. * @returns "Node" string
  15468. */
  15469. Node.prototype.getClassName = function () {
  15470. return "Node";
  15471. };
  15472. Object.defineProperty(Node.prototype, "onDispose", {
  15473. /**
  15474. * Sets a callback that will be raised when the node will be disposed
  15475. */
  15476. set: function (callback) {
  15477. if (this._onDisposeObserver) {
  15478. this.onDisposeObservable.remove(this._onDisposeObserver);
  15479. }
  15480. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15481. },
  15482. enumerable: true,
  15483. configurable: true
  15484. });
  15485. /**
  15486. * Gets the scene of the node
  15487. * @returns a {BABYLON.Scene}
  15488. */
  15489. Node.prototype.getScene = function () {
  15490. return this._scene;
  15491. };
  15492. /**
  15493. * Gets the engine of the node
  15494. * @returns a {BABYLON.Engine}
  15495. */
  15496. Node.prototype.getEngine = function () {
  15497. return this._scene.getEngine();
  15498. };
  15499. /**
  15500. * Attach a behavior to the node
  15501. * @see http://doc.babylonjs.com/features/behaviour
  15502. * @param behavior defines the behavior to attach
  15503. * @returns the current Node
  15504. */
  15505. Node.prototype.addBehavior = function (behavior) {
  15506. var _this = this;
  15507. var index = this._behaviors.indexOf(behavior);
  15508. if (index !== -1) {
  15509. return this;
  15510. }
  15511. behavior.init();
  15512. if (this._scene.isLoading) {
  15513. // We defer the attach when the scene will be loaded
  15514. var observer = this._scene.onDataLoadedObservable.add(function () {
  15515. behavior.attach(_this);
  15516. setTimeout(function () {
  15517. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15518. _this._scene.onDataLoadedObservable.remove(observer);
  15519. }, 0);
  15520. });
  15521. }
  15522. else {
  15523. behavior.attach(this);
  15524. }
  15525. this._behaviors.push(behavior);
  15526. return this;
  15527. };
  15528. /**
  15529. * Remove an attached behavior
  15530. * @see http://doc.babylonjs.com/features/behaviour
  15531. * @param behavior defines the behavior to attach
  15532. * @returns the current Node
  15533. */
  15534. Node.prototype.removeBehavior = function (behavior) {
  15535. var index = this._behaviors.indexOf(behavior);
  15536. if (index === -1) {
  15537. return this;
  15538. }
  15539. this._behaviors[index].detach();
  15540. this._behaviors.splice(index, 1);
  15541. return this;
  15542. };
  15543. Object.defineProperty(Node.prototype, "behaviors", {
  15544. /**
  15545. * Gets the list of attached behaviors
  15546. * @see http://doc.babylonjs.com/features/behaviour
  15547. */
  15548. get: function () {
  15549. return this._behaviors;
  15550. },
  15551. enumerable: true,
  15552. configurable: true
  15553. });
  15554. /**
  15555. * Gets an attached behavior by name
  15556. * @param name defines the name of the behavior to look for
  15557. * @see http://doc.babylonjs.com/features/behaviour
  15558. * @returns null if behavior was not found else the requested behavior
  15559. */
  15560. Node.prototype.getBehaviorByName = function (name) {
  15561. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15562. var behavior = _a[_i];
  15563. if (behavior.name === name) {
  15564. return behavior;
  15565. }
  15566. }
  15567. return null;
  15568. };
  15569. /**
  15570. * Returns the world matrix of the node
  15571. * @returns a matrix containing the node's world matrix
  15572. */
  15573. Node.prototype.getWorldMatrix = function () {
  15574. return BABYLON.Matrix.Identity();
  15575. };
  15576. // override it in derived class if you add new variables to the cache
  15577. // and call the parent class method
  15578. /** @ignore */
  15579. Node.prototype._initCache = function () {
  15580. this._cache = {};
  15581. this._cache.parent = undefined;
  15582. };
  15583. /** @ignore */
  15584. Node.prototype.updateCache = function (force) {
  15585. if (!force && this.isSynchronized())
  15586. return;
  15587. this._cache.parent = this.parent;
  15588. this._updateCache();
  15589. };
  15590. // override it in derived class if you add new variables to the cache
  15591. // and call the parent class method if !ignoreParentClass
  15592. /** @ignore */
  15593. Node.prototype._updateCache = function (ignoreParentClass) {
  15594. };
  15595. // override it in derived class if you add new variables to the cache
  15596. /** @ignore */
  15597. Node.prototype._isSynchronized = function () {
  15598. return true;
  15599. };
  15600. /** @ignore */
  15601. Node.prototype._markSyncedWithParent = function () {
  15602. if (this.parent) {
  15603. this._parentRenderId = this.parent._currentRenderId;
  15604. }
  15605. };
  15606. /** @ignore */
  15607. Node.prototype.isSynchronizedWithParent = function () {
  15608. if (!this.parent) {
  15609. return true;
  15610. }
  15611. if (this._parentRenderId !== this.parent._currentRenderId) {
  15612. return false;
  15613. }
  15614. return this.parent.isSynchronized();
  15615. };
  15616. /** @ignore */
  15617. Node.prototype.isSynchronized = function (updateCache) {
  15618. var check = this.hasNewParent();
  15619. check = check || !this.isSynchronizedWithParent();
  15620. check = check || !this._isSynchronized();
  15621. if (updateCache)
  15622. this.updateCache(true);
  15623. return !check;
  15624. };
  15625. /** @ignore */
  15626. Node.prototype.hasNewParent = function (update) {
  15627. if (this._cache.parent === this.parent)
  15628. return false;
  15629. if (update)
  15630. this._cache.parent = this.parent;
  15631. return true;
  15632. };
  15633. /**
  15634. * Is this node ready to be used/rendered
  15635. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15636. * @return true if the node is ready
  15637. */
  15638. Node.prototype.isReady = function (completeCheck) {
  15639. if (completeCheck === void 0) { completeCheck = false; }
  15640. return this._isReady;
  15641. };
  15642. /**
  15643. * Is this node enabled?
  15644. * 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
  15645. * @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
  15646. * @return whether this node (and its parent) is enabled
  15647. * @see setEnabled
  15648. */
  15649. Node.prototype.isEnabled = function (checkAncestors) {
  15650. if (checkAncestors === void 0) { checkAncestors = true; }
  15651. if (checkAncestors === false) {
  15652. return this._isEnabled;
  15653. }
  15654. if (this._isEnabled === false) {
  15655. return false;
  15656. }
  15657. if (this.parent !== undefined && this.parent !== null) {
  15658. return this.parent.isEnabled(checkAncestors);
  15659. }
  15660. return true;
  15661. };
  15662. /**
  15663. * Set the enabled state of this node
  15664. * @param value defines the new enabled state
  15665. * @see isEnabled
  15666. */
  15667. Node.prototype.setEnabled = function (value) {
  15668. this._isEnabled = value;
  15669. };
  15670. /**
  15671. * Is this node a descendant of the given node?
  15672. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15673. * @param ancestor defines the parent node to inspect
  15674. * @see parent
  15675. * @returns a boolean indicating if this node is a descendant of the given node
  15676. */
  15677. Node.prototype.isDescendantOf = function (ancestor) {
  15678. if (this.parent) {
  15679. if (this.parent === ancestor) {
  15680. return true;
  15681. }
  15682. return this.parent.isDescendantOf(ancestor);
  15683. }
  15684. return false;
  15685. };
  15686. /** @ignore */
  15687. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15688. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15689. if (!this._children) {
  15690. return;
  15691. }
  15692. for (var index = 0; index < this._children.length; index++) {
  15693. var item = this._children[index];
  15694. if (!predicate || predicate(item)) {
  15695. results.push(item);
  15696. }
  15697. if (!directDescendantsOnly) {
  15698. item._getDescendants(results, false, predicate);
  15699. }
  15700. }
  15701. };
  15702. /**
  15703. * Will return all nodes that have this node as ascendant
  15704. * @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
  15705. * @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
  15706. * @return all children nodes of all types
  15707. */
  15708. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15709. var results = new Array();
  15710. this._getDescendants(results, directDescendantsOnly, predicate);
  15711. return results;
  15712. };
  15713. /**
  15714. * Get all child-meshes of this node
  15715. * @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
  15716. * @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
  15717. * @returns an array of {BABYLON.AbstractMesh}
  15718. */
  15719. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15720. var results = [];
  15721. this._getDescendants(results, directDescendantsOnly, function (node) {
  15722. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15723. });
  15724. return results;
  15725. };
  15726. /**
  15727. * Get all child-transformNodes of this node
  15728. * @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
  15729. * @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
  15730. * @returns an array of {BABYLON.TransformNode}
  15731. */
  15732. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15733. var results = [];
  15734. this._getDescendants(results, directDescendantsOnly, function (node) {
  15735. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15736. });
  15737. return results;
  15738. };
  15739. /**
  15740. * Get all direct children of this node
  15741. * @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
  15742. * @returns an array of {BABYLON.Node}
  15743. */
  15744. Node.prototype.getChildren = function (predicate) {
  15745. return this.getDescendants(true, predicate);
  15746. };
  15747. /** @ignore */
  15748. Node.prototype._setReady = function (state) {
  15749. if (state === this._isReady) {
  15750. return;
  15751. }
  15752. if (!state) {
  15753. this._isReady = false;
  15754. return;
  15755. }
  15756. this._isReady = true;
  15757. if (this.onReady) {
  15758. this.onReady(this);
  15759. }
  15760. };
  15761. /**
  15762. * Get an animation by name
  15763. * @param name defines the name of the animation to look for
  15764. * @returns null if not found else the requested animation
  15765. */
  15766. Node.prototype.getAnimationByName = function (name) {
  15767. for (var i = 0; i < this.animations.length; i++) {
  15768. var animation = this.animations[i];
  15769. if (animation.name === name) {
  15770. return animation;
  15771. }
  15772. }
  15773. return null;
  15774. };
  15775. /**
  15776. * Creates an animation range for this node
  15777. * @param name defines the name of the range
  15778. * @param from defines the starting key
  15779. * @param to defines the end key
  15780. */
  15781. Node.prototype.createAnimationRange = function (name, from, to) {
  15782. // check name not already in use
  15783. if (!this._ranges[name]) {
  15784. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15785. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15786. if (this.animations[i]) {
  15787. this.animations[i].createRange(name, from, to);
  15788. }
  15789. }
  15790. }
  15791. };
  15792. /**
  15793. * Delete a specific animation range
  15794. * @param name defines the name of the range to delete
  15795. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15796. */
  15797. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15798. if (deleteFrames === void 0) { deleteFrames = true; }
  15799. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15800. if (this.animations[i]) {
  15801. this.animations[i].deleteRange(name, deleteFrames);
  15802. }
  15803. }
  15804. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15805. };
  15806. /**
  15807. * Get an animation range by name
  15808. * @param name defines the name of the animation range to look for
  15809. * @returns null if not found else the requested animation range
  15810. */
  15811. Node.prototype.getAnimationRange = function (name) {
  15812. return this._ranges[name];
  15813. };
  15814. /**
  15815. * Will start the animation sequence
  15816. * @param name defines the range frames for animation sequence
  15817. * @param loop defines if the animation should loop (false by default)
  15818. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15819. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15820. * @returns the object created for this animation. If range does not exist, it will return null
  15821. */
  15822. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15823. var range = this.getAnimationRange(name);
  15824. if (!range) {
  15825. return null;
  15826. }
  15827. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15828. };
  15829. /**
  15830. * Serialize animation ranges into a JSON compatible object
  15831. * @returns serialization object
  15832. */
  15833. Node.prototype.serializeAnimationRanges = function () {
  15834. var serializationRanges = [];
  15835. for (var name in this._ranges) {
  15836. var localRange = this._ranges[name];
  15837. if (!localRange) {
  15838. continue;
  15839. }
  15840. var range = {};
  15841. range.name = name;
  15842. range.from = localRange.from;
  15843. range.to = localRange.to;
  15844. serializationRanges.push(range);
  15845. }
  15846. return serializationRanges;
  15847. };
  15848. /**
  15849. * Computes the world matrix of the node
  15850. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15851. * @returns the world matrix
  15852. */
  15853. Node.prototype.computeWorldMatrix = function (force) {
  15854. return BABYLON.Matrix.Identity();
  15855. };
  15856. /**
  15857. * Releases resources associated with this node.
  15858. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15859. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15860. */
  15861. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15862. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15863. if (!doNotRecurse) {
  15864. var nodes = this.getDescendants(true);
  15865. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15866. var node = nodes_1[_i];
  15867. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15868. }
  15869. }
  15870. else {
  15871. var transformNodes = this.getChildTransformNodes(true);
  15872. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15873. var transformNode = transformNodes_1[_a];
  15874. transformNode.parent = null;
  15875. transformNode.computeWorldMatrix(true);
  15876. }
  15877. }
  15878. this.parent = null;
  15879. // Callback
  15880. this.onDisposeObservable.notifyObservers(this);
  15881. this.onDisposeObservable.clear();
  15882. // Behaviors
  15883. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  15884. var behavior = _c[_b];
  15885. behavior.detach();
  15886. }
  15887. this._behaviors = [];
  15888. this._isDisposed = true;
  15889. };
  15890. /**
  15891. * Parse animation range data from a serialization object and store them into a given node
  15892. * @param node defines where to store the animation ranges
  15893. * @param parsedNode defines the serialization object to read data from
  15894. * @param scene defines the hosting scene
  15895. */
  15896. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15897. if (parsedNode.ranges) {
  15898. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15899. var data = parsedNode.ranges[index];
  15900. node.createAnimationRange(data.name, data.from, data.to);
  15901. }
  15902. }
  15903. };
  15904. __decorate([
  15905. BABYLON.serialize()
  15906. ], Node.prototype, "name", void 0);
  15907. __decorate([
  15908. BABYLON.serialize()
  15909. ], Node.prototype, "id", void 0);
  15910. __decorate([
  15911. BABYLON.serialize()
  15912. ], Node.prototype, "uniqueId", void 0);
  15913. __decorate([
  15914. BABYLON.serialize()
  15915. ], Node.prototype, "state", void 0);
  15916. __decorate([
  15917. BABYLON.serialize()
  15918. ], Node.prototype, "metadata", void 0);
  15919. return Node;
  15920. }());
  15921. BABYLON.Node = Node;
  15922. })(BABYLON || (BABYLON = {}));
  15923. //# sourceMappingURL=babylon.node.js.map
  15924. var BABYLON;
  15925. (function (BABYLON) {
  15926. var BoundingSphere = /** @class */ (function () {
  15927. function BoundingSphere(minimum, maximum) {
  15928. this.minimum = minimum;
  15929. this.maximum = maximum;
  15930. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15931. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15932. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15933. this.radius = distance * 0.5;
  15934. this.centerWorld = BABYLON.Vector3.Zero();
  15935. this._update(BABYLON.Matrix.Identity());
  15936. }
  15937. // Methods
  15938. BoundingSphere.prototype._update = function (world) {
  15939. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15940. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15941. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15942. };
  15943. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15944. for (var i = 0; i < 6; i++) {
  15945. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15946. return false;
  15947. }
  15948. return true;
  15949. };
  15950. BoundingSphere.prototype.intersectsPoint = function (point) {
  15951. var x = this.centerWorld.x - point.x;
  15952. var y = this.centerWorld.y - point.y;
  15953. var z = this.centerWorld.z - point.z;
  15954. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15955. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15956. return false;
  15957. return true;
  15958. };
  15959. // Statics
  15960. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15961. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15962. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15963. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15964. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15965. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15966. return false;
  15967. return true;
  15968. };
  15969. return BoundingSphere;
  15970. }());
  15971. BABYLON.BoundingSphere = BoundingSphere;
  15972. })(BABYLON || (BABYLON = {}));
  15973. //# sourceMappingURL=babylon.boundingSphere.js.map
  15974. var BABYLON;
  15975. (function (BABYLON) {
  15976. var BoundingBox = /** @class */ (function () {
  15977. function BoundingBox(minimum, maximum) {
  15978. this.minimum = minimum;
  15979. this.maximum = maximum;
  15980. this.vectors = new Array();
  15981. this.vectorsWorld = new Array();
  15982. // Bounding vectors
  15983. this.vectors.push(this.minimum.clone());
  15984. this.vectors.push(this.maximum.clone());
  15985. this.vectors.push(this.minimum.clone());
  15986. this.vectors[2].x = this.maximum.x;
  15987. this.vectors.push(this.minimum.clone());
  15988. this.vectors[3].y = this.maximum.y;
  15989. this.vectors.push(this.minimum.clone());
  15990. this.vectors[4].z = this.maximum.z;
  15991. this.vectors.push(this.maximum.clone());
  15992. this.vectors[5].z = this.minimum.z;
  15993. this.vectors.push(this.maximum.clone());
  15994. this.vectors[6].x = this.minimum.x;
  15995. this.vectors.push(this.maximum.clone());
  15996. this.vectors[7].y = this.minimum.y;
  15997. // OBB
  15998. this.center = this.maximum.add(this.minimum).scale(0.5);
  15999. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16000. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16001. // World
  16002. for (var index = 0; index < this.vectors.length; index++) {
  16003. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16004. }
  16005. this.minimumWorld = BABYLON.Vector3.Zero();
  16006. this.maximumWorld = BABYLON.Vector3.Zero();
  16007. this.centerWorld = BABYLON.Vector3.Zero();
  16008. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16009. this._update(BABYLON.Matrix.Identity());
  16010. }
  16011. // Methods
  16012. BoundingBox.prototype.getWorldMatrix = function () {
  16013. return this._worldMatrix;
  16014. };
  16015. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16016. this._worldMatrix.copyFrom(matrix);
  16017. return this;
  16018. };
  16019. BoundingBox.prototype._update = function (world) {
  16020. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16021. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16022. for (var index = 0; index < this.vectors.length; index++) {
  16023. var v = this.vectorsWorld[index];
  16024. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16025. if (v.x < this.minimumWorld.x)
  16026. this.minimumWorld.x = v.x;
  16027. if (v.y < this.minimumWorld.y)
  16028. this.minimumWorld.y = v.y;
  16029. if (v.z < this.minimumWorld.z)
  16030. this.minimumWorld.z = v.z;
  16031. if (v.x > this.maximumWorld.x)
  16032. this.maximumWorld.x = v.x;
  16033. if (v.y > this.maximumWorld.y)
  16034. this.maximumWorld.y = v.y;
  16035. if (v.z > this.maximumWorld.z)
  16036. this.maximumWorld.z = v.z;
  16037. }
  16038. // Extend
  16039. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16040. this.extendSizeWorld.scaleInPlace(0.5);
  16041. // OBB
  16042. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16043. this.centerWorld.scaleInPlace(0.5);
  16044. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16045. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16046. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16047. this._worldMatrix = world;
  16048. };
  16049. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16050. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16051. };
  16052. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16053. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16054. };
  16055. BoundingBox.prototype.intersectsPoint = function (point) {
  16056. var delta = -BABYLON.Epsilon;
  16057. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16058. return false;
  16059. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16060. return false;
  16061. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16062. return false;
  16063. return true;
  16064. };
  16065. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16066. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16067. };
  16068. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16069. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16070. return false;
  16071. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16072. return false;
  16073. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16074. return false;
  16075. return true;
  16076. };
  16077. // Statics
  16078. BoundingBox.Intersects = function (box0, box1) {
  16079. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16080. return false;
  16081. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16082. return false;
  16083. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16084. return false;
  16085. return true;
  16086. };
  16087. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16088. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16089. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16090. return (num <= (sphereRadius * sphereRadius));
  16091. };
  16092. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16093. for (var p = 0; p < 6; p++) {
  16094. for (var i = 0; i < 8; i++) {
  16095. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16096. return false;
  16097. }
  16098. }
  16099. }
  16100. return true;
  16101. };
  16102. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16103. for (var p = 0; p < 6; p++) {
  16104. var inCount = 8;
  16105. for (var i = 0; i < 8; i++) {
  16106. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16107. --inCount;
  16108. }
  16109. else {
  16110. break;
  16111. }
  16112. }
  16113. if (inCount === 0)
  16114. return false;
  16115. }
  16116. return true;
  16117. };
  16118. return BoundingBox;
  16119. }());
  16120. BABYLON.BoundingBox = BoundingBox;
  16121. })(BABYLON || (BABYLON = {}));
  16122. //# sourceMappingURL=babylon.boundingBox.js.map
  16123. var BABYLON;
  16124. (function (BABYLON) {
  16125. var computeBoxExtents = function (axis, box) {
  16126. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16127. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16128. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16129. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16130. var r = r0 + r1 + r2;
  16131. return {
  16132. min: p - r,
  16133. max: p + r
  16134. };
  16135. };
  16136. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16137. var axisOverlap = function (axis, box0, box1) {
  16138. var result0 = computeBoxExtents(axis, box0);
  16139. var result1 = computeBoxExtents(axis, box1);
  16140. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16141. };
  16142. var BoundingInfo = /** @class */ (function () {
  16143. function BoundingInfo(minimum, maximum) {
  16144. this.minimum = minimum;
  16145. this.maximum = maximum;
  16146. this._isLocked = false;
  16147. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16148. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16149. }
  16150. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16151. get: function () {
  16152. return this._isLocked;
  16153. },
  16154. set: function (value) {
  16155. this._isLocked = value;
  16156. },
  16157. enumerable: true,
  16158. configurable: true
  16159. });
  16160. // Methods
  16161. BoundingInfo.prototype.update = function (world) {
  16162. if (this._isLocked) {
  16163. return;
  16164. }
  16165. this.boundingBox._update(world);
  16166. this.boundingSphere._update(world);
  16167. };
  16168. /**
  16169. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16170. * @param center New center of the bounding info
  16171. * @param extend New extend of the bounding info
  16172. */
  16173. BoundingInfo.prototype.centerOn = function (center, extend) {
  16174. this.minimum = center.subtract(extend);
  16175. this.maximum = center.add(extend);
  16176. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16177. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16178. return this;
  16179. };
  16180. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16181. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16182. return false;
  16183. return this.boundingBox.isInFrustum(frustumPlanes);
  16184. };
  16185. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16186. /**
  16187. * Gets the world distance between the min and max points of the bounding box
  16188. */
  16189. get: function () {
  16190. var boundingBox = this.boundingBox;
  16191. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16192. return size.length();
  16193. },
  16194. enumerable: true,
  16195. configurable: true
  16196. });
  16197. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16198. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16199. };
  16200. BoundingInfo.prototype._checkCollision = function (collider) {
  16201. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16202. };
  16203. BoundingInfo.prototype.intersectsPoint = function (point) {
  16204. if (!this.boundingSphere.centerWorld) {
  16205. return false;
  16206. }
  16207. if (!this.boundingSphere.intersectsPoint(point)) {
  16208. return false;
  16209. }
  16210. if (!this.boundingBox.intersectsPoint(point)) {
  16211. return false;
  16212. }
  16213. return true;
  16214. };
  16215. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16216. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16217. return false;
  16218. }
  16219. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16220. return false;
  16221. }
  16222. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16223. return false;
  16224. }
  16225. if (!precise) {
  16226. return true;
  16227. }
  16228. var box0 = this.boundingBox;
  16229. var box1 = boundingInfo.boundingBox;
  16230. if (!axisOverlap(box0.directions[0], box0, box1))
  16231. return false;
  16232. if (!axisOverlap(box0.directions[1], box0, box1))
  16233. return false;
  16234. if (!axisOverlap(box0.directions[2], box0, box1))
  16235. return false;
  16236. if (!axisOverlap(box1.directions[0], box0, box1))
  16237. return false;
  16238. if (!axisOverlap(box1.directions[1], box0, box1))
  16239. return false;
  16240. if (!axisOverlap(box1.directions[2], box0, box1))
  16241. return false;
  16242. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16243. return false;
  16244. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16245. return false;
  16246. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16247. return false;
  16248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16249. return false;
  16250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16251. return false;
  16252. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16253. return false;
  16254. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16255. return false;
  16256. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16257. return false;
  16258. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16259. return false;
  16260. return true;
  16261. };
  16262. return BoundingInfo;
  16263. }());
  16264. BABYLON.BoundingInfo = BoundingInfo;
  16265. })(BABYLON || (BABYLON = {}));
  16266. //# sourceMappingURL=babylon.boundingInfo.js.map
  16267. var BABYLON;
  16268. (function (BABYLON) {
  16269. var TransformNode = /** @class */ (function (_super) {
  16270. __extends(TransformNode, _super);
  16271. function TransformNode(name, scene, isPure) {
  16272. if (scene === void 0) { scene = null; }
  16273. if (isPure === void 0) { isPure = true; }
  16274. var _this = _super.call(this, name, scene) || this;
  16275. // Properties
  16276. _this._rotation = BABYLON.Vector3.Zero();
  16277. _this._scaling = BABYLON.Vector3.One();
  16278. _this._isDirty = false;
  16279. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16280. _this.scalingDeterminant = 1;
  16281. _this.infiniteDistance = false;
  16282. _this.position = BABYLON.Vector3.Zero();
  16283. _this._localWorld = BABYLON.Matrix.Zero();
  16284. _this._worldMatrix = BABYLON.Matrix.Zero();
  16285. _this._worldMatrixDeterminant = 0;
  16286. _this._absolutePosition = BABYLON.Vector3.Zero();
  16287. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16288. _this._postMultiplyPivotMatrix = false;
  16289. _this._isWorldMatrixFrozen = false;
  16290. /**
  16291. * An event triggered after the world matrix is updated
  16292. * @type {BABYLON.Observable}
  16293. */
  16294. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16295. _this._nonUniformScaling = false;
  16296. if (isPure) {
  16297. _this.getScene().addTransformNode(_this);
  16298. }
  16299. return _this;
  16300. }
  16301. /**
  16302. * Gets a string idenfifying the name of the class
  16303. * @returns "TransformNode" string
  16304. */
  16305. TransformNode.prototype.getClassName = function () {
  16306. return "TransformNode";
  16307. };
  16308. Object.defineProperty(TransformNode.prototype, "rotation", {
  16309. /**
  16310. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16311. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16312. * Default : (0.0, 0.0, 0.0)
  16313. */
  16314. get: function () {
  16315. return this._rotation;
  16316. },
  16317. set: function (newRotation) {
  16318. this._rotation = newRotation;
  16319. },
  16320. enumerable: true,
  16321. configurable: true
  16322. });
  16323. Object.defineProperty(TransformNode.prototype, "scaling", {
  16324. /**
  16325. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16326. * Default : (1.0, 1.0, 1.0)
  16327. */
  16328. get: function () {
  16329. return this._scaling;
  16330. },
  16331. /**
  16332. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16333. * Default : (1.0, 1.0, 1.0)
  16334. */
  16335. set: function (newScaling) {
  16336. this._scaling = newScaling;
  16337. },
  16338. enumerable: true,
  16339. configurable: true
  16340. });
  16341. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16342. /**
  16343. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16344. * It's null by default.
  16345. * 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)
  16346. */
  16347. get: function () {
  16348. return this._rotationQuaternion;
  16349. },
  16350. set: function (quaternion) {
  16351. this._rotationQuaternion = quaternion;
  16352. //reset the rotation vector.
  16353. if (quaternion && this.rotation.length()) {
  16354. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16355. }
  16356. },
  16357. enumerable: true,
  16358. configurable: true
  16359. });
  16360. /**
  16361. * Returns the latest update of the World matrix
  16362. * Returns a Matrix.
  16363. */
  16364. TransformNode.prototype.getWorldMatrix = function () {
  16365. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16366. this.computeWorldMatrix();
  16367. }
  16368. return this._worldMatrix;
  16369. };
  16370. /**
  16371. * Returns the latest update of the World matrix determinant.
  16372. */
  16373. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16374. return this._worldMatrixDeterminant;
  16375. };
  16376. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16377. /**
  16378. * Returns directly the latest state of the mesh World matrix.
  16379. * A Matrix is returned.
  16380. */
  16381. get: function () {
  16382. return this._worldMatrix;
  16383. },
  16384. enumerable: true,
  16385. configurable: true
  16386. });
  16387. /**
  16388. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16389. * Returns the AbstractMesh.
  16390. */
  16391. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16392. this._poseMatrix.copyFrom(matrix);
  16393. return this;
  16394. };
  16395. /**
  16396. * Returns the mesh Pose matrix.
  16397. * Returned object : Matrix
  16398. */
  16399. TransformNode.prototype.getPoseMatrix = function () {
  16400. return this._poseMatrix;
  16401. };
  16402. TransformNode.prototype._isSynchronized = function () {
  16403. if (this._isDirty) {
  16404. return false;
  16405. }
  16406. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16407. return false;
  16408. if (this._cache.pivotMatrixUpdated) {
  16409. return false;
  16410. }
  16411. if (this.infiniteDistance) {
  16412. return false;
  16413. }
  16414. if (!this._cache.position.equals(this.position))
  16415. return false;
  16416. if (this.rotationQuaternion) {
  16417. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16418. return false;
  16419. }
  16420. if (!this._cache.rotation.equals(this.rotation))
  16421. return false;
  16422. if (!this._cache.scaling.equals(this.scaling))
  16423. return false;
  16424. return true;
  16425. };
  16426. TransformNode.prototype._initCache = function () {
  16427. _super.prototype._initCache.call(this);
  16428. this._cache.localMatrixUpdated = false;
  16429. this._cache.position = BABYLON.Vector3.Zero();
  16430. this._cache.scaling = BABYLON.Vector3.Zero();
  16431. this._cache.rotation = BABYLON.Vector3.Zero();
  16432. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16433. this._cache.billboardMode = -1;
  16434. };
  16435. TransformNode.prototype.markAsDirty = function (property) {
  16436. if (property === "rotation") {
  16437. this.rotationQuaternion = null;
  16438. }
  16439. this._currentRenderId = Number.MAX_VALUE;
  16440. this._isDirty = true;
  16441. return this;
  16442. };
  16443. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16444. /**
  16445. * Returns the current mesh absolute position.
  16446. * Retuns a Vector3.
  16447. */
  16448. get: function () {
  16449. return this._absolutePosition;
  16450. },
  16451. enumerable: true,
  16452. configurable: true
  16453. });
  16454. /**
  16455. * Sets a new matrix to apply before all other transformation
  16456. * @param matrix defines the transform matrix
  16457. * @returns the current TransformNode
  16458. */
  16459. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16460. return this.setPivotMatrix(matrix, false);
  16461. };
  16462. /**
  16463. * Sets a new pivot matrix to the current node
  16464. * @param matrix defines the new pivot matrix to use
  16465. * @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
  16466. * @returns the current TransformNode
  16467. */
  16468. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16469. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16470. this._pivotMatrix = matrix.clone();
  16471. this._cache.pivotMatrixUpdated = true;
  16472. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16473. if (this._postMultiplyPivotMatrix) {
  16474. if (!this._pivotMatrixInverse) {
  16475. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16476. }
  16477. else {
  16478. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16479. }
  16480. }
  16481. return this;
  16482. };
  16483. /**
  16484. * Returns the mesh pivot matrix.
  16485. * Default : Identity.
  16486. * A Matrix is returned.
  16487. */
  16488. TransformNode.prototype.getPivotMatrix = function () {
  16489. return this._pivotMatrix;
  16490. };
  16491. /**
  16492. * Prevents the World matrix to be computed any longer.
  16493. * Returns the AbstractMesh.
  16494. */
  16495. TransformNode.prototype.freezeWorldMatrix = function () {
  16496. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16497. this.computeWorldMatrix(true);
  16498. this._isWorldMatrixFrozen = true;
  16499. return this;
  16500. };
  16501. /**
  16502. * Allows back the World matrix computation.
  16503. * Returns the AbstractMesh.
  16504. */
  16505. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16506. this._isWorldMatrixFrozen = false;
  16507. this.computeWorldMatrix(true);
  16508. return this;
  16509. };
  16510. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16511. /**
  16512. * True if the World matrix has been frozen.
  16513. * Returns a boolean.
  16514. */
  16515. get: function () {
  16516. return this._isWorldMatrixFrozen;
  16517. },
  16518. enumerable: true,
  16519. configurable: true
  16520. });
  16521. /**
  16522. * Retuns the mesh absolute position in the World.
  16523. * Returns a Vector3.
  16524. */
  16525. TransformNode.prototype.getAbsolutePosition = function () {
  16526. this.computeWorldMatrix();
  16527. return this._absolutePosition;
  16528. };
  16529. /**
  16530. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16531. * Returns the AbstractMesh.
  16532. */
  16533. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16534. if (!absolutePosition) {
  16535. return this;
  16536. }
  16537. var absolutePositionX;
  16538. var absolutePositionY;
  16539. var absolutePositionZ;
  16540. if (absolutePosition.x === undefined) {
  16541. if (arguments.length < 3) {
  16542. return this;
  16543. }
  16544. absolutePositionX = arguments[0];
  16545. absolutePositionY = arguments[1];
  16546. absolutePositionZ = arguments[2];
  16547. }
  16548. else {
  16549. absolutePositionX = absolutePosition.x;
  16550. absolutePositionY = absolutePosition.y;
  16551. absolutePositionZ = absolutePosition.z;
  16552. }
  16553. if (this.parent) {
  16554. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16555. invertParentWorldMatrix.invert();
  16556. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16557. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16558. }
  16559. else {
  16560. this.position.x = absolutePositionX;
  16561. this.position.y = absolutePositionY;
  16562. this.position.z = absolutePositionZ;
  16563. }
  16564. return this;
  16565. };
  16566. /**
  16567. * Sets the mesh position in its local space.
  16568. * Returns the AbstractMesh.
  16569. */
  16570. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16571. this.computeWorldMatrix();
  16572. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16573. return this;
  16574. };
  16575. /**
  16576. * Returns the mesh position in the local space from the current World matrix values.
  16577. * Returns a new Vector3.
  16578. */
  16579. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16580. this.computeWorldMatrix();
  16581. var invLocalWorldMatrix = this._localWorld.clone();
  16582. invLocalWorldMatrix.invert();
  16583. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16584. };
  16585. /**
  16586. * Translates the mesh along the passed Vector3 in its local space.
  16587. * Returns the AbstractMesh.
  16588. */
  16589. TransformNode.prototype.locallyTranslate = function (vector3) {
  16590. this.computeWorldMatrix(true);
  16591. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16592. return this;
  16593. };
  16594. /**
  16595. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16596. * @param targetPoint the position (must be in same space as current mesh) to look at
  16597. * @param yawCor optional yaw (y-axis) correction in radians
  16598. * @param pitchCor optional pitch (x-axis) correction in radians
  16599. * @param rollCor optional roll (z-axis) correction in radians
  16600. * @param space the choosen space of the target
  16601. * @returns the TransformNode.
  16602. */
  16603. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16604. if (yawCor === void 0) { yawCor = 0; }
  16605. if (pitchCor === void 0) { pitchCor = 0; }
  16606. if (rollCor === void 0) { rollCor = 0; }
  16607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16608. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16609. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16610. targetPoint.subtractToRef(pos, dv);
  16611. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16612. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16613. var pitch = Math.atan2(dv.y, len);
  16614. if (this.rotationQuaternion) {
  16615. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16616. }
  16617. else {
  16618. this.rotation.x = pitch + pitchCor;
  16619. this.rotation.y = yaw + yawCor;
  16620. this.rotation.z = rollCor;
  16621. }
  16622. return this;
  16623. };
  16624. /**
  16625. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16626. * This Vector3 is expressed in the World space.
  16627. */
  16628. TransformNode.prototype.getDirection = function (localAxis) {
  16629. var result = BABYLON.Vector3.Zero();
  16630. this.getDirectionToRef(localAxis, result);
  16631. return result;
  16632. };
  16633. /**
  16634. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16635. * localAxis is expressed in the mesh local space.
  16636. * result is computed in the Wordl space from the mesh World matrix.
  16637. * Returns the AbstractMesh.
  16638. */
  16639. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16640. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16641. return this;
  16642. };
  16643. /**
  16644. * Sets a new pivot point to the current node
  16645. * @param point defines the new pivot point to use
  16646. * @param space defines if the point is in world or local space (local by default)
  16647. * @returns the current TransformNode
  16648. */
  16649. TransformNode.prototype.setPivotPoint = function (point, space) {
  16650. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16651. if (this.getScene().getRenderId() == 0) {
  16652. this.computeWorldMatrix(true);
  16653. }
  16654. var wm = this.getWorldMatrix();
  16655. if (space == BABYLON.Space.WORLD) {
  16656. var tmat = BABYLON.Tmp.Matrix[0];
  16657. wm.invertToRef(tmat);
  16658. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16659. }
  16660. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16661. };
  16662. /**
  16663. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16664. */
  16665. TransformNode.prototype.getPivotPoint = function () {
  16666. var point = BABYLON.Vector3.Zero();
  16667. this.getPivotPointToRef(point);
  16668. return point;
  16669. };
  16670. /**
  16671. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16672. * Returns the AbstractMesh.
  16673. */
  16674. TransformNode.prototype.getPivotPointToRef = function (result) {
  16675. result.x = -this._pivotMatrix.m[12];
  16676. result.y = -this._pivotMatrix.m[13];
  16677. result.z = -this._pivotMatrix.m[14];
  16678. return this;
  16679. };
  16680. /**
  16681. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16682. */
  16683. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16684. var point = BABYLON.Vector3.Zero();
  16685. this.getAbsolutePivotPointToRef(point);
  16686. return point;
  16687. };
  16688. /**
  16689. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16690. * Returns the AbstractMesh.
  16691. */
  16692. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16693. result.x = this._pivotMatrix.m[12];
  16694. result.y = this._pivotMatrix.m[13];
  16695. result.z = this._pivotMatrix.m[14];
  16696. this.getPivotPointToRef(result);
  16697. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16698. return this;
  16699. };
  16700. /**
  16701. * Defines the passed node as the parent of the current node.
  16702. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16703. * Returns the TransformNode.
  16704. */
  16705. TransformNode.prototype.setParent = function (node) {
  16706. if (node === null) {
  16707. var rotation = BABYLON.Tmp.Quaternion[0];
  16708. var position = BABYLON.Tmp.Vector3[0];
  16709. var scale = BABYLON.Tmp.Vector3[1];
  16710. if (this.parent && this.parent.computeWorldMatrix) {
  16711. this.parent.computeWorldMatrix(true);
  16712. }
  16713. this.computeWorldMatrix(true);
  16714. this.getWorldMatrix().decompose(scale, rotation, position);
  16715. if (this.rotationQuaternion) {
  16716. this.rotationQuaternion.copyFrom(rotation);
  16717. }
  16718. else {
  16719. rotation.toEulerAnglesToRef(this.rotation);
  16720. }
  16721. this.scaling.x = scale.x;
  16722. this.scaling.y = scale.y;
  16723. this.scaling.z = scale.z;
  16724. this.position.x = position.x;
  16725. this.position.y = position.y;
  16726. this.position.z = position.z;
  16727. }
  16728. else {
  16729. var rotation = BABYLON.Tmp.Quaternion[0];
  16730. var position = BABYLON.Tmp.Vector3[0];
  16731. var scale = BABYLON.Tmp.Vector3[1];
  16732. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16733. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16734. this.computeWorldMatrix(true);
  16735. node.computeWorldMatrix(true);
  16736. node.getWorldMatrix().invertToRef(invParentMatrix);
  16737. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16738. diffMatrix.decompose(scale, rotation, position);
  16739. if (this.rotationQuaternion) {
  16740. this.rotationQuaternion.copyFrom(rotation);
  16741. }
  16742. else {
  16743. rotation.toEulerAnglesToRef(this.rotation);
  16744. }
  16745. this.position.x = position.x;
  16746. this.position.y = position.y;
  16747. this.position.z = position.z;
  16748. this.scaling.x = scale.x;
  16749. this.scaling.y = scale.y;
  16750. this.scaling.z = scale.z;
  16751. }
  16752. this.parent = node;
  16753. return this;
  16754. };
  16755. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16756. get: function () {
  16757. return this._nonUniformScaling;
  16758. },
  16759. enumerable: true,
  16760. configurable: true
  16761. });
  16762. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16763. if (this._nonUniformScaling === value) {
  16764. return false;
  16765. }
  16766. this._nonUniformScaling = true;
  16767. return true;
  16768. };
  16769. /**
  16770. * Attach the current TransformNode to another TransformNode associated with a bone
  16771. * @param bone Bone affecting the TransformNode
  16772. * @param affectedTransformNode TransformNode associated with the bone
  16773. */
  16774. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16775. this._transformToBoneReferal = affectedTransformNode;
  16776. this.parent = bone;
  16777. if (bone.getWorldMatrix().determinant() < 0) {
  16778. this.scalingDeterminant *= -1;
  16779. }
  16780. return this;
  16781. };
  16782. TransformNode.prototype.detachFromBone = function () {
  16783. if (!this.parent) {
  16784. return this;
  16785. }
  16786. if (this.parent.getWorldMatrix().determinant() < 0) {
  16787. this.scalingDeterminant *= -1;
  16788. }
  16789. this._transformToBoneReferal = null;
  16790. this.parent = null;
  16791. return this;
  16792. };
  16793. /**
  16794. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16795. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16796. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16797. * The passed axis is also normalized.
  16798. * Returns the AbstractMesh.
  16799. */
  16800. TransformNode.prototype.rotate = function (axis, amount, space) {
  16801. axis.normalize();
  16802. if (!this.rotationQuaternion) {
  16803. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16804. this.rotation = BABYLON.Vector3.Zero();
  16805. }
  16806. var rotationQuaternion;
  16807. if (!space || space === BABYLON.Space.LOCAL) {
  16808. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16809. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16810. }
  16811. else {
  16812. if (this.parent) {
  16813. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16814. invertParentWorldMatrix.invert();
  16815. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16816. }
  16817. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16818. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16819. }
  16820. return this;
  16821. };
  16822. /**
  16823. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16824. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16825. * The passed axis is also normalized.
  16826. * Returns the AbstractMesh.
  16827. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16828. */
  16829. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16830. axis.normalize();
  16831. if (!this.rotationQuaternion) {
  16832. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16833. this.rotation.copyFromFloats(0, 0, 0);
  16834. }
  16835. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16836. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16837. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16838. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16839. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16840. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16841. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16842. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16843. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16844. return this;
  16845. };
  16846. /**
  16847. * Translates the mesh along the axis vector for the passed distance in the given space.
  16848. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16849. * Returns the AbstractMesh.
  16850. */
  16851. TransformNode.prototype.translate = function (axis, distance, space) {
  16852. var displacementVector = axis.scale(distance);
  16853. if (!space || space === BABYLON.Space.LOCAL) {
  16854. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16855. this.setPositionWithLocalVector(tempV3);
  16856. }
  16857. else {
  16858. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16859. }
  16860. return this;
  16861. };
  16862. /**
  16863. * Adds a rotation step to the mesh current rotation.
  16864. * x, y, z are Euler angles expressed in radians.
  16865. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16866. * This means this rotation is made in the mesh local space only.
  16867. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16868. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16869. * ```javascript
  16870. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16871. * ```
  16872. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16873. * 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.
  16874. * Returns the AbstractMesh.
  16875. */
  16876. TransformNode.prototype.addRotation = function (x, y, z) {
  16877. var rotationQuaternion;
  16878. if (this.rotationQuaternion) {
  16879. rotationQuaternion = this.rotationQuaternion;
  16880. }
  16881. else {
  16882. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16883. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16884. }
  16885. var accumulation = BABYLON.Tmp.Quaternion[0];
  16886. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16887. rotationQuaternion.multiplyInPlace(accumulation);
  16888. if (!this.rotationQuaternion) {
  16889. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16890. }
  16891. return this;
  16892. };
  16893. /**
  16894. * Computes the mesh World matrix and returns it.
  16895. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16896. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16897. * If the parameter `force`is set to `true`, the actual computation is done.
  16898. * Returns the mesh World Matrix.
  16899. */
  16900. TransformNode.prototype.computeWorldMatrix = function (force) {
  16901. if (this._isWorldMatrixFrozen) {
  16902. return this._worldMatrix;
  16903. }
  16904. if (!force && this.isSynchronized(true)) {
  16905. return this._worldMatrix;
  16906. }
  16907. this._cache.position.copyFrom(this.position);
  16908. this._cache.scaling.copyFrom(this.scaling);
  16909. this._cache.pivotMatrixUpdated = false;
  16910. this._cache.billboardMode = this.billboardMode;
  16911. this._currentRenderId = this.getScene().getRenderId();
  16912. this._isDirty = false;
  16913. // Scaling
  16914. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16915. // Rotation
  16916. //rotate, if quaternion is set and rotation was used
  16917. if (this.rotationQuaternion) {
  16918. var len = this.rotation.length();
  16919. if (len) {
  16920. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16921. this.rotation.copyFromFloats(0, 0, 0);
  16922. }
  16923. }
  16924. if (this.rotationQuaternion) {
  16925. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16926. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16927. }
  16928. else {
  16929. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16930. this._cache.rotation.copyFrom(this.rotation);
  16931. }
  16932. // Translation
  16933. var camera = this.getScene().activeCamera;
  16934. if (this.infiniteDistance && !this.parent && camera) {
  16935. var cameraWorldMatrix = camera.getWorldMatrix();
  16936. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16937. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16938. }
  16939. else {
  16940. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16941. }
  16942. // Composing transformations
  16943. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16944. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16945. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16946. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16947. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16948. // Need to decompose each rotation here
  16949. var currentPosition = BABYLON.Tmp.Vector3[3];
  16950. if (this.parent && this.parent.getWorldMatrix) {
  16951. if (this._transformToBoneReferal) {
  16952. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16953. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16954. }
  16955. else {
  16956. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16957. }
  16958. }
  16959. else {
  16960. currentPosition.copyFrom(this.position);
  16961. }
  16962. currentPosition.subtractInPlace(camera.globalPosition);
  16963. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16964. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16965. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16966. }
  16967. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16968. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16969. }
  16970. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16971. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16972. }
  16973. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16974. }
  16975. else {
  16976. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16977. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16978. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16979. }
  16980. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16981. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16982. }
  16983. // Local world
  16984. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16985. // Parent
  16986. if (this.parent && this.parent.getWorldMatrix) {
  16987. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16988. if (this._transformToBoneReferal) {
  16989. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16990. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16991. }
  16992. else {
  16993. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16994. }
  16995. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16996. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16997. this._worldMatrix.copyFrom(this._localWorld);
  16998. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16999. }
  17000. else {
  17001. if (this._transformToBoneReferal) {
  17002. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17003. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17004. }
  17005. else {
  17006. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17007. }
  17008. }
  17009. this._markSyncedWithParent();
  17010. }
  17011. else {
  17012. this._worldMatrix.copyFrom(this._localWorld);
  17013. }
  17014. // Post multiply inverse of pivotMatrix
  17015. if (this._postMultiplyPivotMatrix) {
  17016. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17017. }
  17018. // Normal matrix
  17019. if (this.scaling.isNonUniform) {
  17020. this._updateNonUniformScalingState(true);
  17021. }
  17022. else if (this.parent && this.parent._nonUniformScaling) {
  17023. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17024. }
  17025. else {
  17026. this._updateNonUniformScalingState(false);
  17027. }
  17028. this._afterComputeWorldMatrix();
  17029. // Absolute position
  17030. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17031. // Callbacks
  17032. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17033. if (!this._poseMatrix) {
  17034. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17035. }
  17036. // Cache the determinant
  17037. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17038. return this._worldMatrix;
  17039. };
  17040. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17041. };
  17042. /**
  17043. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17044. * @param func: callback function to add
  17045. *
  17046. * Returns the TransformNode.
  17047. */
  17048. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17049. this.onAfterWorldMatrixUpdateObservable.add(func);
  17050. return this;
  17051. };
  17052. /**
  17053. * Removes a registered callback function.
  17054. * Returns the TransformNode.
  17055. */
  17056. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17057. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17058. return this;
  17059. };
  17060. /**
  17061. * Clone the current transform node
  17062. * Returns the new transform node
  17063. * @param name Name of the new clone
  17064. * @param newParent New parent for the clone
  17065. * @param doNotCloneChildren Do not clone children hierarchy
  17066. */
  17067. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17068. var _this = this;
  17069. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17070. result.name = name;
  17071. result.id = name;
  17072. if (newParent) {
  17073. result.parent = newParent;
  17074. }
  17075. if (!doNotCloneChildren) {
  17076. // Children
  17077. var directDescendants = this.getDescendants(true);
  17078. for (var index = 0; index < directDescendants.length; index++) {
  17079. var child = directDescendants[index];
  17080. if (child.clone) {
  17081. child.clone(name + "." + child.name, result);
  17082. }
  17083. }
  17084. }
  17085. return result;
  17086. };
  17087. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17088. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17089. serializationObject.type = this.getClassName();
  17090. // Parent
  17091. if (this.parent) {
  17092. serializationObject.parentId = this.parent.id;
  17093. }
  17094. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17095. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17096. }
  17097. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17098. serializationObject.isEnabled = this.isEnabled();
  17099. // Parent
  17100. if (this.parent) {
  17101. serializationObject.parentId = this.parent.id;
  17102. }
  17103. return serializationObject;
  17104. };
  17105. // Statics
  17106. /**
  17107. * Returns a new TransformNode object parsed from the source provided.
  17108. * The parameter `parsedMesh` is the source.
  17109. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17110. */
  17111. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17112. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17113. if (BABYLON.Tags) {
  17114. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17115. }
  17116. if (parsedTransformNode.localMatrix) {
  17117. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17118. }
  17119. else if (parsedTransformNode.pivotMatrix) {
  17120. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17121. }
  17122. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17123. // Parent
  17124. if (parsedTransformNode.parentId) {
  17125. transformNode._waitingParentId = parsedTransformNode.parentId;
  17126. }
  17127. return transformNode;
  17128. };
  17129. /**
  17130. * Releases resources associated with this transform node.
  17131. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17132. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17133. */
  17134. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17135. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17136. // Animations
  17137. this.getScene().stopAnimation(this);
  17138. // Remove from scene
  17139. this.getScene().removeTransformNode(this);
  17140. this.onAfterWorldMatrixUpdateObservable.clear();
  17141. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17142. };
  17143. // Statics
  17144. TransformNode.BILLBOARDMODE_NONE = 0;
  17145. TransformNode.BILLBOARDMODE_X = 1;
  17146. TransformNode.BILLBOARDMODE_Y = 2;
  17147. TransformNode.BILLBOARDMODE_Z = 4;
  17148. TransformNode.BILLBOARDMODE_ALL = 7;
  17149. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17150. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17151. __decorate([
  17152. BABYLON.serializeAsVector3()
  17153. ], TransformNode.prototype, "_rotation", void 0);
  17154. __decorate([
  17155. BABYLON.serializeAsQuaternion()
  17156. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17157. __decorate([
  17158. BABYLON.serializeAsVector3()
  17159. ], TransformNode.prototype, "_scaling", void 0);
  17160. __decorate([
  17161. BABYLON.serialize()
  17162. ], TransformNode.prototype, "billboardMode", void 0);
  17163. __decorate([
  17164. BABYLON.serialize()
  17165. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17166. __decorate([
  17167. BABYLON.serialize()
  17168. ], TransformNode.prototype, "infiniteDistance", void 0);
  17169. __decorate([
  17170. BABYLON.serializeAsVector3()
  17171. ], TransformNode.prototype, "position", void 0);
  17172. return TransformNode;
  17173. }(BABYLON.Node));
  17174. BABYLON.TransformNode = TransformNode;
  17175. })(BABYLON || (BABYLON = {}));
  17176. //# sourceMappingURL=babylon.transformNode.js.map
  17177. var BABYLON;
  17178. (function (BABYLON) {
  17179. var AbstractMesh = /** @class */ (function (_super) {
  17180. __extends(AbstractMesh, _super);
  17181. // Constructor
  17182. function AbstractMesh(name, scene) {
  17183. if (scene === void 0) { scene = null; }
  17184. var _this = _super.call(this, name, scene, false) || this;
  17185. _this._facetNb = 0; // facet number
  17186. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17187. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17188. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17189. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17190. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17191. _this._subDiv = {
  17192. max: 1,
  17193. X: 1,
  17194. Y: 1,
  17195. Z: 1
  17196. };
  17197. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17198. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17199. // Events
  17200. /**
  17201. * An event triggered when this mesh collides with another one
  17202. * @type {BABYLON.Observable}
  17203. */
  17204. _this.onCollideObservable = new BABYLON.Observable();
  17205. /**
  17206. * An event triggered when the collision's position changes
  17207. * @type {BABYLON.Observable}
  17208. */
  17209. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17210. /**
  17211. * An event triggered when material is changed
  17212. * @type {BABYLON.Observable}
  17213. */
  17214. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17215. // Properties
  17216. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17217. /**
  17218. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17219. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17220. * or
  17221. * 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.
  17222. * for more info check WebGl documentations
  17223. */
  17224. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17225. /**
  17226. * 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:
  17227. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17228. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17229. * 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.
  17230. */
  17231. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17232. /**
  17233. * 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.
  17234. * The default value is -1 which means don't break the query and wait till the result.
  17235. */
  17236. _this.occlusionRetryCount = -1;
  17237. _this._occlusionInternalRetryCounter = 0;
  17238. _this._isOccluded = false;
  17239. _this._isOcclusionQueryInProgress = false;
  17240. _this._visibility = 1.0;
  17241. _this.alphaIndex = Number.MAX_VALUE;
  17242. _this.isVisible = true;
  17243. _this.isPickable = true;
  17244. _this.showBoundingBox = false;
  17245. _this.showSubMeshesBoundingBox = false;
  17246. _this.isBlocker = false;
  17247. _this.enablePointerMoveEvents = false;
  17248. _this.renderingGroupId = 0;
  17249. _this._receiveShadows = false;
  17250. _this.renderOutline = false;
  17251. _this.outlineColor = BABYLON.Color3.Red();
  17252. _this.outlineWidth = 0.02;
  17253. _this.renderOverlay = false;
  17254. _this.overlayColor = BABYLON.Color3.Red();
  17255. _this.overlayAlpha = 0.5;
  17256. _this._hasVertexAlpha = false;
  17257. _this._useVertexColors = true;
  17258. _this._computeBonesUsingShaders = true;
  17259. _this._numBoneInfluencers = 4;
  17260. _this._applyFog = true;
  17261. _this.useOctreeForRenderingSelection = true;
  17262. _this.useOctreeForPicking = true;
  17263. _this.useOctreeForCollisions = true;
  17264. _this._layerMask = 0x0FFFFFFF;
  17265. /**
  17266. * True if the mesh must be rendered in any case.
  17267. */
  17268. _this.alwaysSelectAsActiveMesh = false;
  17269. /**
  17270. * This scene's action manager
  17271. * @type {BABYLON.ActionManager}
  17272. */
  17273. _this.actionManager = null;
  17274. // Physics
  17275. _this.physicsImpostor = null;
  17276. // Collisions
  17277. _this._checkCollisions = false;
  17278. _this._collisionMask = -1;
  17279. _this._collisionGroup = -1;
  17280. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17281. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17282. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17283. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17284. // Edges
  17285. _this.edgesWidth = 1;
  17286. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17287. // Cache
  17288. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17289. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17290. _this._renderId = 0;
  17291. _this._intersectionsInProgress = new Array();
  17292. _this._unIndexed = false;
  17293. _this._lightSources = new Array();
  17294. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17295. if (collidedMesh === void 0) { collidedMesh = null; }
  17296. //TODO move this to the collision coordinator!
  17297. if (_this.getScene().workerCollisions)
  17298. newPosition.multiplyInPlace(_this._collider._radius);
  17299. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17300. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17301. _this.position.addInPlace(_this._diffPositionForCollisions);
  17302. }
  17303. if (collidedMesh) {
  17304. _this.onCollideObservable.notifyObservers(collidedMesh);
  17305. }
  17306. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17307. };
  17308. _this.getScene().addMesh(_this);
  17309. _this._resyncLightSources();
  17310. return _this;
  17311. }
  17312. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17313. get: function () {
  17314. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17315. },
  17316. enumerable: true,
  17317. configurable: true
  17318. });
  17319. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17320. get: function () {
  17321. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17322. },
  17323. enumerable: true,
  17324. configurable: true
  17325. });
  17326. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17327. get: function () {
  17328. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17329. },
  17330. enumerable: true,
  17331. configurable: true
  17332. });
  17333. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17334. get: function () {
  17335. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17336. },
  17337. enumerable: true,
  17338. configurable: true
  17339. });
  17340. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17341. get: function () {
  17342. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17343. },
  17344. enumerable: true,
  17345. configurable: true
  17346. });
  17347. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17348. /**
  17349. * Read-only : the number of facets in the mesh
  17350. */
  17351. get: function () {
  17352. return this._facetNb;
  17353. },
  17354. enumerable: true,
  17355. configurable: true
  17356. });
  17357. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17358. /**
  17359. * The number (integer) of subdivisions per axis in the partioning space
  17360. */
  17361. get: function () {
  17362. return this._partitioningSubdivisions;
  17363. },
  17364. set: function (nb) {
  17365. this._partitioningSubdivisions = nb;
  17366. },
  17367. enumerable: true,
  17368. configurable: true
  17369. });
  17370. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17371. /**
  17372. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17373. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17374. */
  17375. get: function () {
  17376. return this._partitioningBBoxRatio;
  17377. },
  17378. set: function (ratio) {
  17379. this._partitioningBBoxRatio = ratio;
  17380. },
  17381. enumerable: true,
  17382. configurable: true
  17383. });
  17384. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17385. /**
  17386. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17387. * Works only for updatable meshes.
  17388. * Doesn't work with multi-materials.
  17389. */
  17390. get: function () {
  17391. return this._facetDepthSort;
  17392. },
  17393. set: function (sort) {
  17394. this._facetDepthSort = sort;
  17395. },
  17396. enumerable: true,
  17397. configurable: true
  17398. });
  17399. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17400. /**
  17401. * The location (Vector3) where the facet depth sort must be computed from.
  17402. * By default, the active camera position.
  17403. * Used only when facet depth sort is enabled.
  17404. */
  17405. get: function () {
  17406. return this._facetDepthSortFrom;
  17407. },
  17408. set: function (location) {
  17409. this._facetDepthSortFrom = location;
  17410. },
  17411. enumerable: true,
  17412. configurable: true
  17413. });
  17414. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17415. /**
  17416. * Read-only boolean : is the feature facetData enabled ?
  17417. */
  17418. get: function () {
  17419. return this._facetDataEnabled;
  17420. },
  17421. enumerable: true,
  17422. configurable: true
  17423. });
  17424. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17425. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17426. return false;
  17427. }
  17428. this._markSubMeshesAsMiscDirty();
  17429. return true;
  17430. };
  17431. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17432. set: function (callback) {
  17433. if (this._onCollideObserver) {
  17434. this.onCollideObservable.remove(this._onCollideObserver);
  17435. }
  17436. this._onCollideObserver = this.onCollideObservable.add(callback);
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17442. set: function (callback) {
  17443. if (this._onCollisionPositionChangeObserver) {
  17444. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17445. }
  17446. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17447. },
  17448. enumerable: true,
  17449. configurable: true
  17450. });
  17451. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17452. /**
  17453. * 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.
  17454. */
  17455. get: function () {
  17456. return this._isOccluded;
  17457. },
  17458. set: function (value) {
  17459. this._isOccluded = value;
  17460. },
  17461. enumerable: true,
  17462. configurable: true
  17463. });
  17464. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17465. /**
  17466. * Flag to check the progress status of the query
  17467. */
  17468. get: function () {
  17469. return this._isOcclusionQueryInProgress;
  17470. },
  17471. enumerable: true,
  17472. configurable: true
  17473. });
  17474. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17475. /**
  17476. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17477. */
  17478. get: function () {
  17479. return this._visibility;
  17480. },
  17481. /**
  17482. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17483. */
  17484. set: function (value) {
  17485. if (this._visibility === value) {
  17486. return;
  17487. }
  17488. this._visibility = value;
  17489. this._markSubMeshesAsMiscDirty();
  17490. },
  17491. enumerable: true,
  17492. configurable: true
  17493. });
  17494. Object.defineProperty(AbstractMesh.prototype, "material", {
  17495. get: function () {
  17496. return this._material;
  17497. },
  17498. set: function (value) {
  17499. if (this._material === value) {
  17500. return;
  17501. }
  17502. this._material = value;
  17503. if (this.onMaterialChangedObservable.hasObservers) {
  17504. this.onMaterialChangedObservable.notifyObservers(this);
  17505. }
  17506. if (!this.subMeshes) {
  17507. return;
  17508. }
  17509. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17510. var subMesh = _a[_i];
  17511. subMesh.setEffect(null);
  17512. }
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17518. get: function () {
  17519. return this._receiveShadows;
  17520. },
  17521. set: function (value) {
  17522. if (this._receiveShadows === value) {
  17523. return;
  17524. }
  17525. this._receiveShadows = value;
  17526. this._markSubMeshesAsLightDirty();
  17527. },
  17528. enumerable: true,
  17529. configurable: true
  17530. });
  17531. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17532. get: function () {
  17533. return this._hasVertexAlpha;
  17534. },
  17535. set: function (value) {
  17536. if (this._hasVertexAlpha === value) {
  17537. return;
  17538. }
  17539. this._hasVertexAlpha = value;
  17540. this._markSubMeshesAsAttributesDirty();
  17541. this._markSubMeshesAsMiscDirty();
  17542. },
  17543. enumerable: true,
  17544. configurable: true
  17545. });
  17546. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17547. get: function () {
  17548. return this._useVertexColors;
  17549. },
  17550. set: function (value) {
  17551. if (this._useVertexColors === value) {
  17552. return;
  17553. }
  17554. this._useVertexColors = value;
  17555. this._markSubMeshesAsAttributesDirty();
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17561. get: function () {
  17562. return this._computeBonesUsingShaders;
  17563. },
  17564. set: function (value) {
  17565. if (this._computeBonesUsingShaders === value) {
  17566. return;
  17567. }
  17568. this._computeBonesUsingShaders = value;
  17569. this._markSubMeshesAsAttributesDirty();
  17570. },
  17571. enumerable: true,
  17572. configurable: true
  17573. });
  17574. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17575. get: function () {
  17576. return this._numBoneInfluencers;
  17577. },
  17578. set: function (value) {
  17579. if (this._numBoneInfluencers === value) {
  17580. return;
  17581. }
  17582. this._numBoneInfluencers = value;
  17583. this._markSubMeshesAsAttributesDirty();
  17584. },
  17585. enumerable: true,
  17586. configurable: true
  17587. });
  17588. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17589. get: function () {
  17590. return this._applyFog;
  17591. },
  17592. set: function (value) {
  17593. if (this._applyFog === value) {
  17594. return;
  17595. }
  17596. this._applyFog = value;
  17597. this._markSubMeshesAsMiscDirty();
  17598. },
  17599. enumerable: true,
  17600. configurable: true
  17601. });
  17602. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17603. get: function () {
  17604. return this._layerMask;
  17605. },
  17606. set: function (value) {
  17607. if (value === this._layerMask) {
  17608. return;
  17609. }
  17610. this._layerMask = value;
  17611. this._resyncLightSources();
  17612. },
  17613. enumerable: true,
  17614. configurable: true
  17615. });
  17616. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17617. get: function () {
  17618. return this._collisionMask;
  17619. },
  17620. set: function (mask) {
  17621. this._collisionMask = !isNaN(mask) ? mask : -1;
  17622. },
  17623. enumerable: true,
  17624. configurable: true
  17625. });
  17626. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17627. get: function () {
  17628. return this._collisionGroup;
  17629. },
  17630. set: function (mask) {
  17631. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17632. },
  17633. enumerable: true,
  17634. configurable: true
  17635. });
  17636. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17637. get: function () {
  17638. return null;
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17644. get: function () {
  17645. return this._skeleton;
  17646. },
  17647. set: function (value) {
  17648. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17649. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17650. }
  17651. if (value && value.needInitialSkinMatrix) {
  17652. value._registerMeshWithPoseMatrix(this);
  17653. }
  17654. this._skeleton = value;
  17655. if (!this._skeleton) {
  17656. this._bonesTransformMatrices = null;
  17657. }
  17658. this._markSubMeshesAsAttributesDirty();
  17659. },
  17660. enumerable: true,
  17661. configurable: true
  17662. });
  17663. /**
  17664. * Returns the string "AbstractMesh"
  17665. */
  17666. AbstractMesh.prototype.getClassName = function () {
  17667. return "AbstractMesh";
  17668. };
  17669. /**
  17670. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17671. */
  17672. AbstractMesh.prototype.toString = function (fullDetails) {
  17673. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17674. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17675. if (this._skeleton) {
  17676. ret += ", skeleton: " + this._skeleton.name;
  17677. }
  17678. if (fullDetails) {
  17679. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17680. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17681. }
  17682. return ret;
  17683. };
  17684. AbstractMesh.prototype._rebuild = function () {
  17685. if (this._occlusionQuery) {
  17686. this._occlusionQuery = null;
  17687. }
  17688. if (this._edgesRenderer) {
  17689. this._edgesRenderer._rebuild();
  17690. }
  17691. if (!this.subMeshes) {
  17692. return;
  17693. }
  17694. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17695. var subMesh = _a[_i];
  17696. subMesh._rebuild();
  17697. }
  17698. };
  17699. AbstractMesh.prototype._resyncLightSources = function () {
  17700. this._lightSources.length = 0;
  17701. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17702. var light = _a[_i];
  17703. if (!light.isEnabled()) {
  17704. continue;
  17705. }
  17706. if (light.canAffectMesh(this)) {
  17707. this._lightSources.push(light);
  17708. }
  17709. }
  17710. this._markSubMeshesAsLightDirty();
  17711. };
  17712. AbstractMesh.prototype._resyncLighSource = function (light) {
  17713. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17714. var index = this._lightSources.indexOf(light);
  17715. if (index === -1) {
  17716. if (!isIn) {
  17717. return;
  17718. }
  17719. this._lightSources.push(light);
  17720. }
  17721. else {
  17722. if (isIn) {
  17723. return;
  17724. }
  17725. this._lightSources.splice(index, 1);
  17726. }
  17727. this._markSubMeshesAsLightDirty();
  17728. };
  17729. AbstractMesh.prototype._removeLightSource = function (light) {
  17730. var index = this._lightSources.indexOf(light);
  17731. if (index === -1) {
  17732. return;
  17733. }
  17734. this._lightSources.splice(index, 1);
  17735. this._markSubMeshesAsLightDirty();
  17736. };
  17737. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17738. if (!this.subMeshes) {
  17739. return;
  17740. }
  17741. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17742. var subMesh = _a[_i];
  17743. if (subMesh._materialDefines) {
  17744. func(subMesh._materialDefines);
  17745. }
  17746. }
  17747. };
  17748. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17749. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17750. };
  17751. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17752. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17753. };
  17754. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17755. if (!this.subMeshes) {
  17756. return;
  17757. }
  17758. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17759. var subMesh = _a[_i];
  17760. var material = subMesh.getMaterial();
  17761. if (material) {
  17762. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17763. }
  17764. }
  17765. };
  17766. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17767. /**
  17768. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17769. * Default : (1.0, 1.0, 1.0)
  17770. */
  17771. get: function () {
  17772. return this._scaling;
  17773. },
  17774. /**
  17775. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17776. * Default : (1.0, 1.0, 1.0)
  17777. */
  17778. set: function (newScaling) {
  17779. this._scaling = newScaling;
  17780. if (this.physicsImpostor) {
  17781. this.physicsImpostor.forceUpdate();
  17782. }
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. // Methods
  17788. /**
  17789. * Disables the mesh edger rendering mode.
  17790. * Returns the AbstractMesh.
  17791. */
  17792. AbstractMesh.prototype.disableEdgesRendering = function () {
  17793. if (this._edgesRenderer) {
  17794. this._edgesRenderer.dispose();
  17795. this._edgesRenderer = null;
  17796. }
  17797. return this;
  17798. };
  17799. /**
  17800. * Enables the edge rendering mode on the mesh.
  17801. * This mode makes the mesh edges visible.
  17802. * Returns the AbstractMesh.
  17803. */
  17804. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17805. if (epsilon === void 0) { epsilon = 0.95; }
  17806. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17807. this.disableEdgesRendering();
  17808. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17809. return this;
  17810. };
  17811. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17812. /**
  17813. * Returns true if the mesh is blocked. Used by the class Mesh.
  17814. * Returns the boolean `false` by default.
  17815. */
  17816. get: function () {
  17817. return false;
  17818. },
  17819. enumerable: true,
  17820. configurable: true
  17821. });
  17822. /**
  17823. * Returns the mesh itself by default, used by the class Mesh.
  17824. * Returned type : AbstractMesh
  17825. */
  17826. AbstractMesh.prototype.getLOD = function (camera) {
  17827. return this;
  17828. };
  17829. /**
  17830. * Returns 0 by default, used by the class Mesh.
  17831. * Returns an integer.
  17832. */
  17833. AbstractMesh.prototype.getTotalVertices = function () {
  17834. return 0;
  17835. };
  17836. /**
  17837. * Returns null by default, used by the class Mesh.
  17838. * Returned type : integer array
  17839. */
  17840. AbstractMesh.prototype.getIndices = function () {
  17841. return null;
  17842. };
  17843. /**
  17844. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17845. * Returned type : float array or Float32Array
  17846. */
  17847. AbstractMesh.prototype.getVerticesData = function (kind) {
  17848. return null;
  17849. };
  17850. /**
  17851. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17852. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17853. * The `data` are either a numeric array either a Float32Array.
  17854. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17855. * 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).
  17856. * Note that a new underlying VertexBuffer object is created each call.
  17857. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17858. *
  17859. * Possible `kind` values :
  17860. * - BABYLON.VertexBuffer.PositionKind
  17861. * - BABYLON.VertexBuffer.UVKind
  17862. * - BABYLON.VertexBuffer.UV2Kind
  17863. * - BABYLON.VertexBuffer.UV3Kind
  17864. * - BABYLON.VertexBuffer.UV4Kind
  17865. * - BABYLON.VertexBuffer.UV5Kind
  17866. * - BABYLON.VertexBuffer.UV6Kind
  17867. * - BABYLON.VertexBuffer.ColorKind
  17868. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17869. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17870. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17871. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17872. *
  17873. * Returns the Mesh.
  17874. */
  17875. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17876. return this;
  17877. };
  17878. /**
  17879. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17880. * If the mesh has no geometry, it is simply returned as it is.
  17881. * The `data` are either a numeric array either a Float32Array.
  17882. * No new underlying VertexBuffer object is created.
  17883. * 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.
  17884. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17885. *
  17886. * Possible `kind` values :
  17887. * - BABYLON.VertexBuffer.PositionKind
  17888. * - BABYLON.VertexBuffer.UVKind
  17889. * - BABYLON.VertexBuffer.UV2Kind
  17890. * - BABYLON.VertexBuffer.UV3Kind
  17891. * - BABYLON.VertexBuffer.UV4Kind
  17892. * - BABYLON.VertexBuffer.UV5Kind
  17893. * - BABYLON.VertexBuffer.UV6Kind
  17894. * - BABYLON.VertexBuffer.ColorKind
  17895. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17896. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17897. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17898. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17899. *
  17900. * Returns the Mesh.
  17901. */
  17902. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17903. return this;
  17904. };
  17905. /**
  17906. * Sets the mesh indices.
  17907. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17908. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17909. * This method creates a new index buffer each call.
  17910. * Returns the Mesh.
  17911. */
  17912. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17913. return this;
  17914. };
  17915. /** Returns false by default, used by the class Mesh.
  17916. * Returns a boolean
  17917. */
  17918. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17919. return false;
  17920. };
  17921. /**
  17922. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17923. * Returns a BoundingInfo
  17924. */
  17925. AbstractMesh.prototype.getBoundingInfo = function () {
  17926. if (this._masterMesh) {
  17927. return this._masterMesh.getBoundingInfo();
  17928. }
  17929. if (!this._boundingInfo) {
  17930. // this._boundingInfo is being created here
  17931. this._updateBoundingInfo();
  17932. }
  17933. // cannot be null.
  17934. return this._boundingInfo;
  17935. };
  17936. /**
  17937. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17938. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17939. */
  17940. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17941. if (includeDescendants === void 0) { includeDescendants = true; }
  17942. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17943. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17944. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17945. if (maxDimension === 0) {
  17946. return this;
  17947. }
  17948. var scale = 1 / maxDimension;
  17949. this.scaling.scaleInPlace(scale);
  17950. return this;
  17951. };
  17952. /**
  17953. * Sets a mesh new object BoundingInfo.
  17954. * Returns the AbstractMesh.
  17955. */
  17956. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17957. this._boundingInfo = boundingInfo;
  17958. return this;
  17959. };
  17960. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17961. get: function () {
  17962. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17963. },
  17964. enumerable: true,
  17965. configurable: true
  17966. });
  17967. AbstractMesh.prototype._preActivate = function () {
  17968. };
  17969. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17970. };
  17971. AbstractMesh.prototype._activate = function (renderId) {
  17972. this._renderId = renderId;
  17973. };
  17974. /**
  17975. * Returns the latest update of the World matrix
  17976. * Returns a Matrix.
  17977. */
  17978. AbstractMesh.prototype.getWorldMatrix = function () {
  17979. if (this._masterMesh) {
  17980. return this._masterMesh.getWorldMatrix();
  17981. }
  17982. return _super.prototype.getWorldMatrix.call(this);
  17983. };
  17984. /**
  17985. * Returns the latest update of the World matrix determinant.
  17986. */
  17987. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17988. if (this._masterMesh) {
  17989. return this._masterMesh._getWorldMatrixDeterminant();
  17990. }
  17991. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17992. };
  17993. // ================================== Point of View Movement =================================
  17994. /**
  17995. * Perform relative position change from the point of view of behind the front of the mesh.
  17996. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17997. * Supports definition of mesh facing forward or backward.
  17998. * @param {number} amountRight
  17999. * @param {number} amountUp
  18000. * @param {number} amountForward
  18001. *
  18002. * Returns the AbstractMesh.
  18003. */
  18004. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18005. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18006. return this;
  18007. };
  18008. /**
  18009. * Calculate relative position change from the point of view of behind the front of the mesh.
  18010. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18011. * Supports definition of mesh facing forward or backward.
  18012. * @param {number} amountRight
  18013. * @param {number} amountUp
  18014. * @param {number} amountForward
  18015. *
  18016. * Returns a new Vector3.
  18017. */
  18018. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18019. var rotMatrix = new BABYLON.Matrix();
  18020. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18021. rotQuaternion.toRotationMatrix(rotMatrix);
  18022. var translationDelta = BABYLON.Vector3.Zero();
  18023. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18024. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18025. return translationDelta;
  18026. };
  18027. // ================================== Point of View Rotation =================================
  18028. /**
  18029. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18030. * Supports definition of mesh facing forward or backward.
  18031. * @param {number} flipBack
  18032. * @param {number} twirlClockwise
  18033. * @param {number} tiltRight
  18034. *
  18035. * Returns the AbstractMesh.
  18036. */
  18037. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18038. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18039. return this;
  18040. };
  18041. /**
  18042. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18043. * Supports definition of mesh facing forward or backward.
  18044. * @param {number} flipBack
  18045. * @param {number} twirlClockwise
  18046. * @param {number} tiltRight
  18047. *
  18048. * Returns a new Vector3.
  18049. */
  18050. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18051. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18052. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18053. };
  18054. /**
  18055. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18056. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18057. */
  18058. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18059. if (includeDescendants === void 0) { includeDescendants = true; }
  18060. this.computeWorldMatrix(true);
  18061. var min;
  18062. var max;
  18063. var boundingInfo = this.getBoundingInfo();
  18064. if (!this.subMeshes) {
  18065. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18066. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18067. }
  18068. else {
  18069. min = boundingInfo.boundingBox.minimumWorld;
  18070. max = boundingInfo.boundingBox.maximumWorld;
  18071. }
  18072. if (includeDescendants) {
  18073. var descendants = this.getDescendants(false);
  18074. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18075. var descendant = descendants_1[_i];
  18076. var childMesh = descendant;
  18077. childMesh.computeWorldMatrix(true);
  18078. //make sure we have the needed params to get mix and max
  18079. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18080. continue;
  18081. }
  18082. var childBoundingInfo = childMesh.getBoundingInfo();
  18083. var boundingBox = childBoundingInfo.boundingBox;
  18084. var minBox = boundingBox.minimumWorld;
  18085. var maxBox = boundingBox.maximumWorld;
  18086. BABYLON.Tools.CheckExtends(minBox, min, max);
  18087. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18088. }
  18089. }
  18090. return {
  18091. min: min,
  18092. max: max
  18093. };
  18094. };
  18095. /**
  18096. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18097. * Returns the AbstractMesh.
  18098. */
  18099. AbstractMesh.prototype._updateBoundingInfo = function () {
  18100. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18101. this._boundingInfo.update(this.worldMatrixFromCache);
  18102. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18103. return this;
  18104. };
  18105. /**
  18106. * Update a mesh's children BoundingInfo objects only.
  18107. * Returns the AbstractMesh.
  18108. */
  18109. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18110. if (!this.subMeshes) {
  18111. return this;
  18112. }
  18113. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18114. var subMesh = this.subMeshes[subIndex];
  18115. if (!subMesh.IsGlobal) {
  18116. subMesh.updateBoundingInfo(matrix);
  18117. }
  18118. }
  18119. return this;
  18120. };
  18121. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18122. // Bounding info
  18123. this._updateBoundingInfo();
  18124. };
  18125. /**
  18126. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18127. * A mesh is in the frustum if its bounding box intersects the frustum.
  18128. * Boolean returned.
  18129. */
  18130. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18131. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18132. };
  18133. /**
  18134. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18135. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18136. * Boolean returned.
  18137. */
  18138. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18139. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18140. ;
  18141. };
  18142. /**
  18143. * True if the mesh intersects another mesh or a SolidParticle object.
  18144. * 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)
  18145. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18146. * Returns a boolean.
  18147. */
  18148. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18149. if (precise === void 0) { precise = false; }
  18150. if (!this._boundingInfo || !mesh._boundingInfo) {
  18151. return false;
  18152. }
  18153. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18154. return true;
  18155. }
  18156. if (includeDescendants) {
  18157. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18158. var child = _a[_i];
  18159. if (child.intersectsMesh(mesh, precise, true)) {
  18160. return true;
  18161. }
  18162. }
  18163. }
  18164. return false;
  18165. };
  18166. /**
  18167. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18168. * Returns a boolean.
  18169. */
  18170. AbstractMesh.prototype.intersectsPoint = function (point) {
  18171. if (!this._boundingInfo) {
  18172. return false;
  18173. }
  18174. return this._boundingInfo.intersectsPoint(point);
  18175. };
  18176. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18177. return this.physicsImpostor;
  18178. };
  18179. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18180. if (camera === void 0) { camera = null; }
  18181. if (!camera) {
  18182. camera = this.getScene().activeCamera;
  18183. }
  18184. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18185. };
  18186. /**
  18187. * Returns the distance from the mesh to the active camera.
  18188. * Returns a float.
  18189. */
  18190. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18191. if (camera === void 0) { camera = null; }
  18192. if (!camera) {
  18193. camera = this.getScene().activeCamera;
  18194. }
  18195. return this.absolutePosition.subtract(camera.position).length();
  18196. };
  18197. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18198. if (!this.physicsImpostor) {
  18199. return this;
  18200. }
  18201. this.physicsImpostor.applyImpulse(force, contactPoint);
  18202. return this;
  18203. };
  18204. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18205. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18206. return this;
  18207. }
  18208. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18209. mainPivot: pivot1,
  18210. connectedPivot: pivot2,
  18211. nativeParams: options
  18212. });
  18213. return this;
  18214. };
  18215. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18216. // Collisions
  18217. /**
  18218. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18219. * Default `false`.
  18220. */
  18221. get: function () {
  18222. return this._checkCollisions;
  18223. },
  18224. set: function (collisionEnabled) {
  18225. this._checkCollisions = collisionEnabled;
  18226. if (this.getScene().workerCollisions) {
  18227. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18228. }
  18229. },
  18230. enumerable: true,
  18231. configurable: true
  18232. });
  18233. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18234. /**
  18235. * Gets Collider object used to compute collisions (not physics)
  18236. */
  18237. get: function () {
  18238. return this._collider;
  18239. },
  18240. enumerable: true,
  18241. configurable: true
  18242. });
  18243. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18244. var globalPosition = this.getAbsolutePosition();
  18245. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18246. if (!this._collider) {
  18247. this._collider = new BABYLON.Collider();
  18248. }
  18249. this._collider._radius = this.ellipsoid;
  18250. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18251. return this;
  18252. };
  18253. // Submeshes octree
  18254. /**
  18255. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18256. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18257. * Returns an Octree of submeshes.
  18258. */
  18259. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18260. if (maxCapacity === void 0) { maxCapacity = 64; }
  18261. if (maxDepth === void 0) { maxDepth = 2; }
  18262. if (!this._submeshesOctree) {
  18263. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18264. }
  18265. this.computeWorldMatrix(true);
  18266. var boundingInfo = this.getBoundingInfo();
  18267. // Update octree
  18268. var bbox = boundingInfo.boundingBox;
  18269. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18270. return this._submeshesOctree;
  18271. };
  18272. // Collisions
  18273. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18274. this._generatePointsArray();
  18275. if (!this._positions) {
  18276. return this;
  18277. }
  18278. // Transformation
  18279. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18280. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18281. subMesh._lastColliderWorldVertices = [];
  18282. subMesh._trianglePlanes = [];
  18283. var start = subMesh.verticesStart;
  18284. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18285. for (var i = start; i < end; i++) {
  18286. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18287. }
  18288. }
  18289. // Collide
  18290. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18291. if (collider.collisionFound) {
  18292. collider.collidedMesh = this;
  18293. }
  18294. return this;
  18295. };
  18296. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18297. var subMeshes;
  18298. var len;
  18299. // Octrees
  18300. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18301. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18302. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18303. len = intersections.length;
  18304. subMeshes = intersections.data;
  18305. }
  18306. else {
  18307. subMeshes = this.subMeshes;
  18308. len = subMeshes.length;
  18309. }
  18310. for (var index = 0; index < len; index++) {
  18311. var subMesh = subMeshes[index];
  18312. // Bounding test
  18313. if (len > 1 && !subMesh._checkCollision(collider))
  18314. continue;
  18315. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18316. }
  18317. return this;
  18318. };
  18319. AbstractMesh.prototype._checkCollision = function (collider) {
  18320. // Bounding box test
  18321. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18322. return this;
  18323. // Transformation matrix
  18324. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18325. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18326. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18327. return this;
  18328. };
  18329. // Picking
  18330. AbstractMesh.prototype._generatePointsArray = function () {
  18331. return false;
  18332. };
  18333. /**
  18334. * Checks if the passed Ray intersects with the mesh.
  18335. * Returns an object PickingInfo.
  18336. */
  18337. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18338. var pickingInfo = new BABYLON.PickingInfo();
  18339. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18340. return pickingInfo;
  18341. }
  18342. if (!this._generatePointsArray()) {
  18343. return pickingInfo;
  18344. }
  18345. var intersectInfo = null;
  18346. // Octrees
  18347. var subMeshes;
  18348. var len;
  18349. if (this._submeshesOctree && this.useOctreeForPicking) {
  18350. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18351. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18352. len = intersections.length;
  18353. subMeshes = intersections.data;
  18354. }
  18355. else {
  18356. subMeshes = this.subMeshes;
  18357. len = subMeshes.length;
  18358. }
  18359. for (var index = 0; index < len; index++) {
  18360. var subMesh = subMeshes[index];
  18361. // Bounding test
  18362. if (len > 1 && !subMesh.canIntersects(ray))
  18363. continue;
  18364. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18365. if (currentIntersectInfo) {
  18366. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18367. intersectInfo = currentIntersectInfo;
  18368. intersectInfo.subMeshId = index;
  18369. if (fastCheck) {
  18370. break;
  18371. }
  18372. }
  18373. }
  18374. }
  18375. if (intersectInfo) {
  18376. // Get picked point
  18377. var world = this.getWorldMatrix();
  18378. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18379. var direction = ray.direction.clone();
  18380. direction = direction.scale(intersectInfo.distance);
  18381. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18382. var pickedPoint = worldOrigin.add(worldDirection);
  18383. // Return result
  18384. pickingInfo.hit = true;
  18385. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18386. pickingInfo.pickedPoint = pickedPoint;
  18387. pickingInfo.pickedMesh = this;
  18388. pickingInfo.bu = intersectInfo.bu || 0;
  18389. pickingInfo.bv = intersectInfo.bv || 0;
  18390. pickingInfo.faceId = intersectInfo.faceId;
  18391. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18392. return pickingInfo;
  18393. }
  18394. return pickingInfo;
  18395. };
  18396. /**
  18397. * Clones the mesh, used by the class Mesh.
  18398. * Just returns `null` for an AbstractMesh.
  18399. */
  18400. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18401. return null;
  18402. };
  18403. /**
  18404. * Disposes all the mesh submeshes.
  18405. * Returns the AbstractMesh.
  18406. */
  18407. AbstractMesh.prototype.releaseSubMeshes = function () {
  18408. if (this.subMeshes) {
  18409. while (this.subMeshes.length) {
  18410. this.subMeshes[0].dispose();
  18411. }
  18412. }
  18413. else {
  18414. this.subMeshes = new Array();
  18415. }
  18416. return this;
  18417. };
  18418. /**
  18419. * Releases resources associated with this abstract mesh.
  18420. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18421. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18422. */
  18423. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18424. var _this = this;
  18425. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18426. var index;
  18427. // Action manager
  18428. if (this.actionManager !== undefined && this.actionManager !== null) {
  18429. this.actionManager.dispose();
  18430. this.actionManager = null;
  18431. }
  18432. // Skeleton
  18433. this.skeleton = null;
  18434. // Physics
  18435. if (this.physicsImpostor) {
  18436. this.physicsImpostor.dispose();
  18437. }
  18438. // Intersections in progress
  18439. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18440. var other = this._intersectionsInProgress[index];
  18441. var pos = other._intersectionsInProgress.indexOf(this);
  18442. other._intersectionsInProgress.splice(pos, 1);
  18443. }
  18444. this._intersectionsInProgress = [];
  18445. // Lights
  18446. var lights = this.getScene().lights;
  18447. lights.forEach(function (light) {
  18448. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18449. if (meshIndex !== -1) {
  18450. light.includedOnlyMeshes.splice(meshIndex, 1);
  18451. }
  18452. meshIndex = light.excludedMeshes.indexOf(_this);
  18453. if (meshIndex !== -1) {
  18454. light.excludedMeshes.splice(meshIndex, 1);
  18455. }
  18456. // Shadow generators
  18457. var generator = light.getShadowGenerator();
  18458. if (generator) {
  18459. var shadowMap = generator.getShadowMap();
  18460. if (shadowMap && shadowMap.renderList) {
  18461. meshIndex = shadowMap.renderList.indexOf(_this);
  18462. if (meshIndex !== -1) {
  18463. shadowMap.renderList.splice(meshIndex, 1);
  18464. }
  18465. }
  18466. }
  18467. });
  18468. // Edges
  18469. if (this._edgesRenderer) {
  18470. this._edgesRenderer.dispose();
  18471. this._edgesRenderer = null;
  18472. }
  18473. // SubMeshes
  18474. if (this.getClassName() !== "InstancedMesh") {
  18475. this.releaseSubMeshes();
  18476. }
  18477. // Octree
  18478. var sceneOctree = this.getScene().selectionOctree;
  18479. if (sceneOctree !== undefined && sceneOctree !== null) {
  18480. var index = sceneOctree.dynamicContent.indexOf(this);
  18481. if (index !== -1) {
  18482. sceneOctree.dynamicContent.splice(index, 1);
  18483. }
  18484. }
  18485. // Query
  18486. var engine = this.getScene().getEngine();
  18487. if (this._occlusionQuery) {
  18488. this._isOcclusionQueryInProgress = false;
  18489. engine.deleteQuery(this._occlusionQuery);
  18490. this._occlusionQuery = null;
  18491. }
  18492. // Engine
  18493. engine.wipeCaches();
  18494. // Remove from scene
  18495. this.getScene().removeMesh(this);
  18496. if (disposeMaterialAndTextures) {
  18497. if (this.material) {
  18498. this.material.dispose(false, true);
  18499. }
  18500. }
  18501. if (!doNotRecurse) {
  18502. // Particles
  18503. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18504. if (this.getScene().particleSystems[index].emitter === this) {
  18505. this.getScene().particleSystems[index].dispose();
  18506. index--;
  18507. }
  18508. }
  18509. }
  18510. // facet data
  18511. if (this._facetDataEnabled) {
  18512. this.disableFacetData();
  18513. }
  18514. this.onAfterWorldMatrixUpdateObservable.clear();
  18515. this.onCollideObservable.clear();
  18516. this.onCollisionPositionChangeObservable.clear();
  18517. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18518. };
  18519. /**
  18520. * Adds the passed mesh as a child to the current mesh.
  18521. * Returns the AbstractMesh.
  18522. */
  18523. AbstractMesh.prototype.addChild = function (mesh) {
  18524. mesh.setParent(this);
  18525. return this;
  18526. };
  18527. /**
  18528. * Removes the passed mesh from the current mesh children list.
  18529. * Returns the AbstractMesh.
  18530. */
  18531. AbstractMesh.prototype.removeChild = function (mesh) {
  18532. mesh.setParent(null);
  18533. return this;
  18534. };
  18535. // Facet data
  18536. /**
  18537. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18538. * Returns the AbstractMesh.
  18539. */
  18540. AbstractMesh.prototype._initFacetData = function () {
  18541. if (!this._facetNormals) {
  18542. this._facetNormals = new Array();
  18543. }
  18544. if (!this._facetPositions) {
  18545. this._facetPositions = new Array();
  18546. }
  18547. if (!this._facetPartitioning) {
  18548. this._facetPartitioning = new Array();
  18549. }
  18550. this._facetNb = (this.getIndices().length / 3) | 0;
  18551. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18552. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18553. for (var f = 0; f < this._facetNb; f++) {
  18554. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18555. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18556. }
  18557. this._facetDataEnabled = true;
  18558. return this;
  18559. };
  18560. /**
  18561. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18562. * This method can be called within the render loop.
  18563. * 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.
  18564. * Returns the AbstractMesh.
  18565. */
  18566. AbstractMesh.prototype.updateFacetData = function () {
  18567. if (!this._facetDataEnabled) {
  18568. this._initFacetData();
  18569. }
  18570. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18571. var indices = this.getIndices();
  18572. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18573. var bInfo = this.getBoundingInfo();
  18574. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18575. // init arrays, matrix and sort function on first call
  18576. this._facetDepthSortEnabled = true;
  18577. if (indices instanceof Uint16Array) {
  18578. this._depthSortedIndices = new Uint16Array(indices);
  18579. }
  18580. else if (indices instanceof Uint32Array) {
  18581. this._depthSortedIndices = new Uint32Array(indices);
  18582. }
  18583. else {
  18584. var needs32bits = false;
  18585. for (var i = 0; i < indices.length; i++) {
  18586. if (indices[i] > 65535) {
  18587. needs32bits = true;
  18588. break;
  18589. }
  18590. }
  18591. if (needs32bits) {
  18592. this._depthSortedIndices = new Uint32Array(indices);
  18593. }
  18594. else {
  18595. this._depthSortedIndices = new Uint16Array(indices);
  18596. }
  18597. }
  18598. this._facetDepthSortFunction = function (f1, f2) {
  18599. return (f2.sqDistance - f1.sqDistance);
  18600. };
  18601. if (!this._facetDepthSortFrom) {
  18602. var camera = this.getScene().activeCamera;
  18603. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18604. }
  18605. this._depthSortedFacets = [];
  18606. for (var f = 0; f < this._facetNb; f++) {
  18607. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18608. this._depthSortedFacets.push(depthSortedFacet);
  18609. }
  18610. this._invertedMatrix = BABYLON.Matrix.Identity();
  18611. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18612. }
  18613. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18614. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18615. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18616. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18617. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18618. this._subDiv.max = this._partitioningSubdivisions;
  18619. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18620. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18621. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18622. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18623. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18624. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18625. // set the parameters for ComputeNormals()
  18626. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18627. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18628. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18629. this._facetParameters.bInfo = bInfo;
  18630. this._facetParameters.bbSize = this._bbSize;
  18631. this._facetParameters.subDiv = this._subDiv;
  18632. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18633. this._facetParameters.depthSort = this._facetDepthSort;
  18634. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18635. this.computeWorldMatrix(true);
  18636. this._worldMatrix.invertToRef(this._invertedMatrix);
  18637. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18638. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18639. }
  18640. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18641. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18642. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18643. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18644. var l = (this._depthSortedIndices.length / 3) | 0;
  18645. for (var f = 0; f < l; f++) {
  18646. var sind = this._depthSortedFacets[f].ind;
  18647. this._depthSortedIndices[f * 3] = indices[sind];
  18648. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18649. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18650. }
  18651. this.updateIndices(this._depthSortedIndices);
  18652. }
  18653. return this;
  18654. };
  18655. /**
  18656. * Returns the facetLocalNormals array.
  18657. * The normals are expressed in the mesh local space.
  18658. */
  18659. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18660. if (!this._facetNormals) {
  18661. this.updateFacetData();
  18662. }
  18663. return this._facetNormals;
  18664. };
  18665. /**
  18666. * Returns the facetLocalPositions array.
  18667. * The facet positions are expressed in the mesh local space.
  18668. */
  18669. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18670. if (!this._facetPositions) {
  18671. this.updateFacetData();
  18672. }
  18673. return this._facetPositions;
  18674. };
  18675. /**
  18676. * Returns the facetLocalPartioning array.
  18677. */
  18678. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18679. if (!this._facetPartitioning) {
  18680. this.updateFacetData();
  18681. }
  18682. return this._facetPartitioning;
  18683. };
  18684. /**
  18685. * Returns the i-th facet position in the world system.
  18686. * This method allocates a new Vector3 per call.
  18687. */
  18688. AbstractMesh.prototype.getFacetPosition = function (i) {
  18689. var pos = BABYLON.Vector3.Zero();
  18690. this.getFacetPositionToRef(i, pos);
  18691. return pos;
  18692. };
  18693. /**
  18694. * Sets the reference Vector3 with the i-th facet position in the world system.
  18695. * Returns the AbstractMesh.
  18696. */
  18697. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18698. var localPos = (this.getFacetLocalPositions())[i];
  18699. var world = this.getWorldMatrix();
  18700. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18701. return this;
  18702. };
  18703. /**
  18704. * Returns the i-th facet normal in the world system.
  18705. * This method allocates a new Vector3 per call.
  18706. */
  18707. AbstractMesh.prototype.getFacetNormal = function (i) {
  18708. var norm = BABYLON.Vector3.Zero();
  18709. this.getFacetNormalToRef(i, norm);
  18710. return norm;
  18711. };
  18712. /**
  18713. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18714. * Returns the AbstractMesh.
  18715. */
  18716. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18717. var localNorm = (this.getFacetLocalNormals())[i];
  18718. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18719. return this;
  18720. };
  18721. /**
  18722. * 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).
  18723. */
  18724. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18725. var bInfo = this.getBoundingInfo();
  18726. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18727. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18728. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18729. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18730. return null;
  18731. }
  18732. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18733. };
  18734. /**
  18735. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18736. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18737. * 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.
  18738. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18739. * 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.
  18740. */
  18741. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18742. if (checkFace === void 0) { checkFace = false; }
  18743. if (facing === void 0) { facing = true; }
  18744. var world = this.getWorldMatrix();
  18745. var invMat = BABYLON.Tmp.Matrix[5];
  18746. world.invertToRef(invMat);
  18747. var invVect = BABYLON.Tmp.Vector3[8];
  18748. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18749. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18750. if (projected) {
  18751. // tranform the local computed projected vector to world coordinates
  18752. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18753. }
  18754. return closest;
  18755. };
  18756. /**
  18757. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18758. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18759. * 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.
  18760. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18761. * 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.
  18762. */
  18763. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18764. if (checkFace === void 0) { checkFace = false; }
  18765. if (facing === void 0) { facing = true; }
  18766. var closest = null;
  18767. var tmpx = 0.0;
  18768. var tmpy = 0.0;
  18769. var tmpz = 0.0;
  18770. var d = 0.0; // tmp dot facet normal * facet position
  18771. var t0 = 0.0;
  18772. var projx = 0.0;
  18773. var projy = 0.0;
  18774. var projz = 0.0;
  18775. // Get all the facets in the same partitioning block than (x, y, z)
  18776. var facetPositions = this.getFacetLocalPositions();
  18777. var facetNormals = this.getFacetLocalNormals();
  18778. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18779. if (!facetsInBlock) {
  18780. return null;
  18781. }
  18782. // Get the closest facet to (x, y, z)
  18783. var shortest = Number.MAX_VALUE; // init distance vars
  18784. var tmpDistance = shortest;
  18785. var fib; // current facet in the block
  18786. var norm; // current facet normal
  18787. var p0; // current facet barycenter position
  18788. // loop on all the facets in the current partitioning block
  18789. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18790. fib = facetsInBlock[idx];
  18791. norm = facetNormals[fib];
  18792. p0 = facetPositions[fib];
  18793. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18794. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18795. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18796. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18797. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18798. projx = x + norm.x * t0;
  18799. projy = y + norm.y * t0;
  18800. projz = z + norm.z * t0;
  18801. tmpx = projx - x;
  18802. tmpy = projy - y;
  18803. tmpz = projz - z;
  18804. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18805. if (tmpDistance < shortest) {
  18806. shortest = tmpDistance;
  18807. closest = fib;
  18808. if (projected) {
  18809. projected.x = projx;
  18810. projected.y = projy;
  18811. projected.z = projz;
  18812. }
  18813. }
  18814. }
  18815. }
  18816. return closest;
  18817. };
  18818. /**
  18819. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18820. */
  18821. AbstractMesh.prototype.getFacetDataParameters = function () {
  18822. return this._facetParameters;
  18823. };
  18824. /**
  18825. * Disables the feature FacetData and frees the related memory.
  18826. * Returns the AbstractMesh.
  18827. */
  18828. AbstractMesh.prototype.disableFacetData = function () {
  18829. if (this._facetDataEnabled) {
  18830. this._facetDataEnabled = false;
  18831. this._facetPositions = new Array();
  18832. this._facetNormals = new Array();
  18833. this._facetPartitioning = new Array();
  18834. this._facetParameters = null;
  18835. this._depthSortedIndices = new Uint32Array(0);
  18836. }
  18837. return this;
  18838. };
  18839. /**
  18840. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18841. * Returns the mesh.
  18842. */
  18843. AbstractMesh.prototype.updateIndices = function (indices) {
  18844. return this;
  18845. };
  18846. /**
  18847. * The mesh Geometry. Actually used by the Mesh object.
  18848. * Returns a blank geometry object.
  18849. */
  18850. /**
  18851. * Creates new normals data for the mesh.
  18852. * @param updatable.
  18853. */
  18854. AbstractMesh.prototype.createNormals = function (updatable) {
  18855. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18856. var indices = this.getIndices();
  18857. var normals;
  18858. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18859. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18860. }
  18861. else {
  18862. normals = [];
  18863. }
  18864. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18865. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18866. };
  18867. /**
  18868. * Align the mesh with a normal.
  18869. * Returns the mesh.
  18870. */
  18871. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18872. if (!upDirection) {
  18873. upDirection = BABYLON.Axis.Y;
  18874. }
  18875. var axisX = BABYLON.Tmp.Vector3[0];
  18876. var axisZ = BABYLON.Tmp.Vector3[1];
  18877. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18878. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18879. if (this.rotationQuaternion) {
  18880. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18881. }
  18882. else {
  18883. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18884. }
  18885. return this;
  18886. };
  18887. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18888. var engine = this.getEngine();
  18889. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18890. this._isOccluded = false;
  18891. return;
  18892. }
  18893. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18894. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18895. if (isOcclusionQueryAvailable) {
  18896. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18897. this._isOcclusionQueryInProgress = false;
  18898. this._occlusionInternalRetryCounter = 0;
  18899. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18900. }
  18901. else {
  18902. this._occlusionInternalRetryCounter++;
  18903. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18904. this._isOcclusionQueryInProgress = false;
  18905. this._occlusionInternalRetryCounter = 0;
  18906. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18907. // if strict continue the last state of the object.
  18908. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18909. }
  18910. else {
  18911. return;
  18912. }
  18913. }
  18914. }
  18915. var scene = this.getScene();
  18916. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18917. if (!this._occlusionQuery) {
  18918. this._occlusionQuery = engine.createQuery();
  18919. }
  18920. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18921. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18922. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18923. this._isOcclusionQueryInProgress = true;
  18924. };
  18925. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18926. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18927. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18928. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18929. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18930. return AbstractMesh;
  18931. }(BABYLON.TransformNode));
  18932. BABYLON.AbstractMesh = AbstractMesh;
  18933. })(BABYLON || (BABYLON = {}));
  18934. //# sourceMappingURL=babylon.abstractMesh.js.map
  18935. var BABYLON;
  18936. (function (BABYLON) {
  18937. /**
  18938. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18939. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18940. * 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.
  18941. */
  18942. var Light = /** @class */ (function (_super) {
  18943. __extends(Light, _super);
  18944. /**
  18945. * Creates a Light object in the scene.
  18946. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18947. * @param name The firendly name of the light
  18948. * @param scene The scene the light belongs too
  18949. */
  18950. function Light(name, scene) {
  18951. var _this = _super.call(this, name, scene) || this;
  18952. /**
  18953. * Diffuse gives the basic color to an object.
  18954. */
  18955. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18956. /**
  18957. * Specular produces a highlight color on an object.
  18958. * Note: This is note affecting PBR materials.
  18959. */
  18960. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18961. /**
  18962. * Strength of the light.
  18963. * Note: By default it is define in the framework own unit.
  18964. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18965. */
  18966. _this.intensity = 1.0;
  18967. /**
  18968. * Defines how far from the source the light is impacting in scene units.
  18969. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18970. */
  18971. _this.range = Number.MAX_VALUE;
  18972. /**
  18973. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18974. * of light.
  18975. */
  18976. _this._photometricScale = 1.0;
  18977. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18978. _this._radius = 0.00001;
  18979. /**
  18980. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18981. * exceeding the number allowed of the materials.
  18982. */
  18983. _this.renderPriority = 0;
  18984. /**
  18985. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18986. * the current shadow generator.
  18987. */
  18988. _this.shadowEnabled = true;
  18989. _this._excludeWithLayerMask = 0;
  18990. _this._includeOnlyWithLayerMask = 0;
  18991. _this._lightmapMode = 0;
  18992. /**
  18993. * @ignore Internal use only.
  18994. */
  18995. _this._excludedMeshesIds = new Array();
  18996. /**
  18997. * @ignore Internal use only.
  18998. */
  18999. _this._includedOnlyMeshesIds = new Array();
  19000. _this.getScene().addLight(_this);
  19001. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19002. _this._buildUniformLayout();
  19003. _this.includedOnlyMeshes = new Array();
  19004. _this.excludedMeshes = new Array();
  19005. _this._resyncMeshes();
  19006. return _this;
  19007. }
  19008. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19009. /**
  19010. * If every light affecting the material is in this lightmapMode,
  19011. * material.lightmapTexture adds or multiplies
  19012. * (depends on material.useLightmapAsShadowmap)
  19013. * after every other light calculations.
  19014. */
  19015. get: function () {
  19016. return Light._LIGHTMAP_DEFAULT;
  19017. },
  19018. enumerable: true,
  19019. configurable: true
  19020. });
  19021. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19022. /**
  19023. * material.lightmapTexture as only diffuse lighting from this light
  19024. * adds only specular lighting from this light
  19025. * adds dynamic shadows
  19026. */
  19027. get: function () {
  19028. return Light._LIGHTMAP_SPECULAR;
  19029. },
  19030. enumerable: true,
  19031. configurable: true
  19032. });
  19033. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19034. /**
  19035. * material.lightmapTexture as only lighting
  19036. * no light calculation from this light
  19037. * only adds dynamic shadows from this light
  19038. */
  19039. get: function () {
  19040. return Light._LIGHTMAP_SHADOWSONLY;
  19041. },
  19042. enumerable: true,
  19043. configurable: true
  19044. });
  19045. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19046. /**
  19047. * Each light type uses the default quantity according to its type:
  19048. * point/spot lights use luminous intensity
  19049. * directional lights use illuminance
  19050. */
  19051. get: function () {
  19052. return Light._INTENSITYMODE_AUTOMATIC;
  19053. },
  19054. enumerable: true,
  19055. configurable: true
  19056. });
  19057. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19058. /**
  19059. * lumen (lm)
  19060. */
  19061. get: function () {
  19062. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19063. },
  19064. enumerable: true,
  19065. configurable: true
  19066. });
  19067. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19068. /**
  19069. * candela (lm/sr)
  19070. */
  19071. get: function () {
  19072. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19073. },
  19074. enumerable: true,
  19075. configurable: true
  19076. });
  19077. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19078. /**
  19079. * lux (lm/m^2)
  19080. */
  19081. get: function () {
  19082. return Light._INTENSITYMODE_ILLUMINANCE;
  19083. },
  19084. enumerable: true,
  19085. configurable: true
  19086. });
  19087. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19088. /**
  19089. * nit (cd/m^2)
  19090. */
  19091. get: function () {
  19092. return Light._INTENSITYMODE_LUMINANCE;
  19093. },
  19094. enumerable: true,
  19095. configurable: true
  19096. });
  19097. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19098. /**
  19099. * Light type const id of the point light.
  19100. */
  19101. get: function () {
  19102. return Light._LIGHTTYPEID_POINTLIGHT;
  19103. },
  19104. enumerable: true,
  19105. configurable: true
  19106. });
  19107. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19108. /**
  19109. * Light type const id of the directional light.
  19110. */
  19111. get: function () {
  19112. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19113. },
  19114. enumerable: true,
  19115. configurable: true
  19116. });
  19117. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19118. /**
  19119. * Light type const id of the spot light.
  19120. */
  19121. get: function () {
  19122. return Light._LIGHTTYPEID_SPOTLIGHT;
  19123. },
  19124. enumerable: true,
  19125. configurable: true
  19126. });
  19127. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19128. /**
  19129. * Light type const id of the hemispheric light.
  19130. */
  19131. get: function () {
  19132. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19133. },
  19134. enumerable: true,
  19135. configurable: true
  19136. });
  19137. Object.defineProperty(Light.prototype, "intensityMode", {
  19138. /**
  19139. * Gets the photometric scale used to interpret the intensity.
  19140. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19141. */
  19142. get: function () {
  19143. return this._intensityMode;
  19144. },
  19145. /**
  19146. * Sets the photometric scale used to interpret the intensity.
  19147. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19148. */
  19149. set: function (value) {
  19150. this._intensityMode = value;
  19151. this._computePhotometricScale();
  19152. },
  19153. enumerable: true,
  19154. configurable: true
  19155. });
  19156. ;
  19157. ;
  19158. Object.defineProperty(Light.prototype, "radius", {
  19159. /**
  19160. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19161. */
  19162. get: function () {
  19163. return this._radius;
  19164. },
  19165. /**
  19166. * sets the light radius used by PBR Materials to simulate soft area lights.
  19167. */
  19168. set: function (value) {
  19169. this._radius = value;
  19170. this._computePhotometricScale();
  19171. },
  19172. enumerable: true,
  19173. configurable: true
  19174. });
  19175. ;
  19176. ;
  19177. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19178. /**
  19179. * Gets the only meshes impacted by this light.
  19180. */
  19181. get: function () {
  19182. return this._includedOnlyMeshes;
  19183. },
  19184. /**
  19185. * Sets the only meshes impacted by this light.
  19186. */
  19187. set: function (value) {
  19188. this._includedOnlyMeshes = value;
  19189. this._hookArrayForIncludedOnly(value);
  19190. },
  19191. enumerable: true,
  19192. configurable: true
  19193. });
  19194. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19195. /**
  19196. * Gets the meshes not impacted by this light.
  19197. */
  19198. get: function () {
  19199. return this._excludedMeshes;
  19200. },
  19201. /**
  19202. * Sets the meshes not impacted by this light.
  19203. */
  19204. set: function (value) {
  19205. this._excludedMeshes = value;
  19206. this._hookArrayForExcluded(value);
  19207. },
  19208. enumerable: true,
  19209. configurable: true
  19210. });
  19211. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19212. /**
  19213. * Gets the layer id use to find what meshes are not impacted by the light.
  19214. * Inactive if 0
  19215. */
  19216. get: function () {
  19217. return this._excludeWithLayerMask;
  19218. },
  19219. /**
  19220. * Sets the layer id use to find what meshes are not impacted by the light.
  19221. * Inactive if 0
  19222. */
  19223. set: function (value) {
  19224. this._excludeWithLayerMask = value;
  19225. this._resyncMeshes();
  19226. },
  19227. enumerable: true,
  19228. configurable: true
  19229. });
  19230. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19231. /**
  19232. * Gets the layer id use to find what meshes are impacted by the light.
  19233. * Inactive if 0
  19234. */
  19235. get: function () {
  19236. return this._includeOnlyWithLayerMask;
  19237. },
  19238. /**
  19239. * Sets the layer id use to find what meshes are impacted by the light.
  19240. * Inactive if 0
  19241. */
  19242. set: function (value) {
  19243. this._includeOnlyWithLayerMask = value;
  19244. this._resyncMeshes();
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(Light.prototype, "lightmapMode", {
  19250. /**
  19251. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19252. */
  19253. get: function () {
  19254. return this._lightmapMode;
  19255. },
  19256. /**
  19257. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19258. */
  19259. set: function (value) {
  19260. if (this._lightmapMode === value) {
  19261. return;
  19262. }
  19263. this._lightmapMode = value;
  19264. this._markMeshesAsLightDirty();
  19265. },
  19266. enumerable: true,
  19267. configurable: true
  19268. });
  19269. /**
  19270. * Returns the string "Light".
  19271. * @returns the class name
  19272. */
  19273. Light.prototype.getClassName = function () {
  19274. return "Light";
  19275. };
  19276. /**
  19277. * Converts the light information to a readable string for debug purpose.
  19278. * @param fullDetails Supports for multiple levels of logging within scene loading
  19279. * @returns the human readable light info
  19280. */
  19281. Light.prototype.toString = function (fullDetails) {
  19282. var ret = "Name: " + this.name;
  19283. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19284. if (this.animations) {
  19285. for (var i = 0; i < this.animations.length; i++) {
  19286. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19287. }
  19288. }
  19289. if (fullDetails) {
  19290. }
  19291. return ret;
  19292. };
  19293. /**
  19294. * Set the enabled state of this node.
  19295. * @param value - the new enabled state
  19296. * @see isEnabled
  19297. */
  19298. Light.prototype.setEnabled = function (value) {
  19299. _super.prototype.setEnabled.call(this, value);
  19300. this._resyncMeshes();
  19301. };
  19302. /**
  19303. * Returns the Light associated shadow generator if any.
  19304. * @return the associated shadow generator.
  19305. */
  19306. Light.prototype.getShadowGenerator = function () {
  19307. return this._shadowGenerator;
  19308. };
  19309. /**
  19310. * Returns a Vector3, the absolute light position in the World.
  19311. * @returns the world space position of the light
  19312. */
  19313. Light.prototype.getAbsolutePosition = function () {
  19314. return BABYLON.Vector3.Zero();
  19315. };
  19316. /**
  19317. * Specifies if the light will affect the passed mesh.
  19318. * @param mesh The mesh to test against the light
  19319. * @return true the mesh is affected otherwise, false.
  19320. */
  19321. Light.prototype.canAffectMesh = function (mesh) {
  19322. if (!mesh) {
  19323. return true;
  19324. }
  19325. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19326. return false;
  19327. }
  19328. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19329. return false;
  19330. }
  19331. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19332. return false;
  19333. }
  19334. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19335. return false;
  19336. }
  19337. return true;
  19338. };
  19339. /**
  19340. * Computes and Returns the light World matrix.
  19341. * @returns the world matrix
  19342. */
  19343. Light.prototype.getWorldMatrix = function () {
  19344. this._currentRenderId = this.getScene().getRenderId();
  19345. var worldMatrix = this._getWorldMatrix();
  19346. if (this.parent && this.parent.getWorldMatrix) {
  19347. if (!this._parentedWorldMatrix) {
  19348. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19349. }
  19350. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19351. this._markSyncedWithParent();
  19352. return this._parentedWorldMatrix;
  19353. }
  19354. return worldMatrix;
  19355. };
  19356. /**
  19357. * Sort function to order lights for rendering.
  19358. * @param a First Light object to compare to second.
  19359. * @param b Second Light object to compare first.
  19360. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19361. */
  19362. Light.CompareLightsPriority = function (a, b) {
  19363. //shadow-casting lights have priority over non-shadow-casting lights
  19364. //the renderPrioirty is a secondary sort criterion
  19365. if (a.shadowEnabled !== b.shadowEnabled) {
  19366. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19367. }
  19368. return b.renderPriority - a.renderPriority;
  19369. };
  19370. /**
  19371. * Releases resources associated with this node.
  19372. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19373. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19374. */
  19375. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19376. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19377. if (this._shadowGenerator) {
  19378. this._shadowGenerator.dispose();
  19379. this._shadowGenerator = null;
  19380. }
  19381. // Animations
  19382. this.getScene().stopAnimation(this);
  19383. // Remove from meshes
  19384. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19385. var mesh = _a[_i];
  19386. mesh._removeLightSource(this);
  19387. }
  19388. this._uniformBuffer.dispose();
  19389. // Remove from scene
  19390. this.getScene().removeLight(this);
  19391. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19392. };
  19393. /**
  19394. * Returns the light type ID (integer).
  19395. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19396. */
  19397. Light.prototype.getTypeID = function () {
  19398. return 0;
  19399. };
  19400. /**
  19401. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19402. * @returns the scaled intensity in intensity mode unit
  19403. */
  19404. Light.prototype.getScaledIntensity = function () {
  19405. return this._photometricScale * this.intensity;
  19406. };
  19407. /**
  19408. * Returns a new Light object, named "name", from the current one.
  19409. * @param name The name of the cloned light
  19410. * @returns the new created light
  19411. */
  19412. Light.prototype.clone = function (name) {
  19413. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19414. if (!constructor) {
  19415. return null;
  19416. }
  19417. return BABYLON.SerializationHelper.Clone(constructor, this);
  19418. };
  19419. /**
  19420. * Serializes the current light into a Serialization object.
  19421. * @returns the serialized object.
  19422. */
  19423. Light.prototype.serialize = function () {
  19424. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19425. // Type
  19426. serializationObject.type = this.getTypeID();
  19427. // Parent
  19428. if (this.parent) {
  19429. serializationObject.parentId = this.parent.id;
  19430. }
  19431. // Inclusion / exclusions
  19432. if (this.excludedMeshes.length > 0) {
  19433. serializationObject.excludedMeshesIds = [];
  19434. this.excludedMeshes.forEach(function (mesh) {
  19435. serializationObject.excludedMeshesIds.push(mesh.id);
  19436. });
  19437. }
  19438. if (this.includedOnlyMeshes.length > 0) {
  19439. serializationObject.includedOnlyMeshesIds = [];
  19440. this.includedOnlyMeshes.forEach(function (mesh) {
  19441. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19442. });
  19443. }
  19444. // Animations
  19445. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19446. serializationObject.ranges = this.serializeAnimationRanges();
  19447. return serializationObject;
  19448. };
  19449. /**
  19450. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19451. * This new light is named "name" and added to the passed scene.
  19452. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19453. * @param name The friendly name of the light
  19454. * @param scene The scene the new light will belong to
  19455. * @returns the constructor function
  19456. */
  19457. Light.GetConstructorFromName = function (type, name, scene) {
  19458. switch (type) {
  19459. case 0:
  19460. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19461. case 1:
  19462. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19463. case 2:
  19464. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19465. case 3:
  19466. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19467. }
  19468. return null;
  19469. };
  19470. /**
  19471. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19472. * @param parsedLight The JSON representation of the light
  19473. * @param scene The scene to create the parsed light in
  19474. * @returns the created light after parsing
  19475. */
  19476. Light.Parse = function (parsedLight, scene) {
  19477. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19478. if (!constructor) {
  19479. return null;
  19480. }
  19481. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19482. // Inclusion / exclusions
  19483. if (parsedLight.excludedMeshesIds) {
  19484. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19485. }
  19486. if (parsedLight.includedOnlyMeshesIds) {
  19487. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19488. }
  19489. // Parent
  19490. if (parsedLight.parentId) {
  19491. light._waitingParentId = parsedLight.parentId;
  19492. }
  19493. // Animations
  19494. if (parsedLight.animations) {
  19495. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19496. var parsedAnimation = parsedLight.animations[animationIndex];
  19497. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19498. }
  19499. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19500. }
  19501. if (parsedLight.autoAnimate) {
  19502. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19503. }
  19504. return light;
  19505. };
  19506. Light.prototype._hookArrayForExcluded = function (array) {
  19507. var _this = this;
  19508. var oldPush = array.push;
  19509. array.push = function () {
  19510. var items = [];
  19511. for (var _i = 0; _i < arguments.length; _i++) {
  19512. items[_i] = arguments[_i];
  19513. }
  19514. var result = oldPush.apply(array, items);
  19515. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19516. var item = items_1[_a];
  19517. item._resyncLighSource(_this);
  19518. }
  19519. return result;
  19520. };
  19521. var oldSplice = array.splice;
  19522. array.splice = function (index, deleteCount) {
  19523. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19524. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19525. var item = deleted_1[_i];
  19526. item._resyncLighSource(_this);
  19527. }
  19528. return deleted;
  19529. };
  19530. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19531. var item = array_1[_i];
  19532. item._resyncLighSource(this);
  19533. }
  19534. };
  19535. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19536. var _this = this;
  19537. var oldPush = array.push;
  19538. array.push = function () {
  19539. var items = [];
  19540. for (var _i = 0; _i < arguments.length; _i++) {
  19541. items[_i] = arguments[_i];
  19542. }
  19543. var result = oldPush.apply(array, items);
  19544. _this._resyncMeshes();
  19545. return result;
  19546. };
  19547. var oldSplice = array.splice;
  19548. array.splice = function (index, deleteCount) {
  19549. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19550. _this._resyncMeshes();
  19551. return deleted;
  19552. };
  19553. this._resyncMeshes();
  19554. };
  19555. Light.prototype._resyncMeshes = function () {
  19556. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19557. var mesh = _a[_i];
  19558. mesh._resyncLighSource(this);
  19559. }
  19560. };
  19561. /**
  19562. * Forces the meshes to update their light related information in their rendering used effects
  19563. * @ignore Internal Use Only
  19564. */
  19565. Light.prototype._markMeshesAsLightDirty = function () {
  19566. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19567. var mesh = _a[_i];
  19568. if (mesh._lightSources.indexOf(this) !== -1) {
  19569. mesh._markSubMeshesAsLightDirty();
  19570. }
  19571. }
  19572. };
  19573. /**
  19574. * Recomputes the cached photometric scale if needed.
  19575. */
  19576. Light.prototype._computePhotometricScale = function () {
  19577. this._photometricScale = this._getPhotometricScale();
  19578. this.getScene().resetCachedMaterial();
  19579. };
  19580. /**
  19581. * Returns the Photometric Scale according to the light type and intensity mode.
  19582. */
  19583. Light.prototype._getPhotometricScale = function () {
  19584. var photometricScale = 0.0;
  19585. var lightTypeID = this.getTypeID();
  19586. //get photometric mode
  19587. var photometricMode = this.intensityMode;
  19588. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19589. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19590. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19591. }
  19592. else {
  19593. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19594. }
  19595. }
  19596. //compute photometric scale
  19597. switch (lightTypeID) {
  19598. case Light.LIGHTTYPEID_POINTLIGHT:
  19599. case Light.LIGHTTYPEID_SPOTLIGHT:
  19600. switch (photometricMode) {
  19601. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19602. photometricScale = 1.0 / (4.0 * Math.PI);
  19603. break;
  19604. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19605. photometricScale = 1.0;
  19606. break;
  19607. case Light.INTENSITYMODE_LUMINANCE:
  19608. photometricScale = this.radius * this.radius;
  19609. break;
  19610. }
  19611. break;
  19612. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19613. switch (photometricMode) {
  19614. case Light.INTENSITYMODE_ILLUMINANCE:
  19615. photometricScale = 1.0;
  19616. break;
  19617. case Light.INTENSITYMODE_LUMINANCE:
  19618. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19619. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19620. var apexAngleRadians = this.radius;
  19621. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19622. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19623. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19624. photometricScale = solidAngle;
  19625. break;
  19626. }
  19627. break;
  19628. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19629. // No fall off in hemisperic light.
  19630. photometricScale = 1.0;
  19631. break;
  19632. }
  19633. return photometricScale;
  19634. };
  19635. /**
  19636. * Reorder the light in the scene according to their defined priority.
  19637. * @ignore Internal Use Only
  19638. */
  19639. Light.prototype._reorderLightsInScene = function () {
  19640. var scene = this.getScene();
  19641. if (this._renderPriority != 0) {
  19642. scene.requireLightSorting = true;
  19643. }
  19644. this.getScene().sortLightsByPriority();
  19645. };
  19646. //lightmapMode Consts
  19647. Light._LIGHTMAP_DEFAULT = 0;
  19648. Light._LIGHTMAP_SPECULAR = 1;
  19649. Light._LIGHTMAP_SHADOWSONLY = 2;
  19650. // Intensity Mode Consts
  19651. Light._INTENSITYMODE_AUTOMATIC = 0;
  19652. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19653. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19654. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19655. Light._INTENSITYMODE_LUMINANCE = 4;
  19656. // Light types ids const.
  19657. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19658. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19659. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19660. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19661. __decorate([
  19662. BABYLON.serializeAsColor3()
  19663. ], Light.prototype, "diffuse", void 0);
  19664. __decorate([
  19665. BABYLON.serializeAsColor3()
  19666. ], Light.prototype, "specular", void 0);
  19667. __decorate([
  19668. BABYLON.serialize()
  19669. ], Light.prototype, "intensity", void 0);
  19670. __decorate([
  19671. BABYLON.serialize()
  19672. ], Light.prototype, "range", void 0);
  19673. __decorate([
  19674. BABYLON.serialize()
  19675. ], Light.prototype, "intensityMode", null);
  19676. __decorate([
  19677. BABYLON.serialize()
  19678. ], Light.prototype, "radius", null);
  19679. __decorate([
  19680. BABYLON.serialize()
  19681. ], Light.prototype, "_renderPriority", void 0);
  19682. __decorate([
  19683. BABYLON.expandToProperty("_reorderLightsInScene")
  19684. ], Light.prototype, "renderPriority", void 0);
  19685. __decorate([
  19686. BABYLON.serialize()
  19687. ], Light.prototype, "shadowEnabled", void 0);
  19688. __decorate([
  19689. BABYLON.serialize("excludeWithLayerMask")
  19690. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19691. __decorate([
  19692. BABYLON.serialize("includeOnlyWithLayerMask")
  19693. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19694. __decorate([
  19695. BABYLON.serialize("lightmapMode")
  19696. ], Light.prototype, "_lightmapMode", void 0);
  19697. return Light;
  19698. }(BABYLON.Node));
  19699. BABYLON.Light = Light;
  19700. })(BABYLON || (BABYLON = {}));
  19701. //# sourceMappingURL=babylon.light.js.map
  19702. var BABYLON;
  19703. (function (BABYLON) {
  19704. var Camera = /** @class */ (function (_super) {
  19705. __extends(Camera, _super);
  19706. function Camera(name, position, scene) {
  19707. var _this = _super.call(this, name, scene) || this;
  19708. /**
  19709. * The vector the camera should consider as up.
  19710. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19711. */
  19712. _this.upVector = BABYLON.Vector3.Up();
  19713. _this.orthoLeft = null;
  19714. _this.orthoRight = null;
  19715. _this.orthoBottom = null;
  19716. _this.orthoTop = null;
  19717. /**
  19718. * FOV is set in Radians. (default is 0.8)
  19719. */
  19720. _this.fov = 0.8;
  19721. _this.minZ = 1;
  19722. _this.maxZ = 10000.0;
  19723. _this.inertia = 0.9;
  19724. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19725. _this.isIntermediate = false;
  19726. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19727. /**
  19728. * Restricts the camera to viewing objects with the same layerMask.
  19729. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19730. */
  19731. _this.layerMask = 0x0FFFFFFF;
  19732. /**
  19733. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19734. */
  19735. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19736. // Camera rig members
  19737. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19738. _this._rigCameras = new Array();
  19739. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19740. _this._skipRendering = false;
  19741. _this.customRenderTargets = new Array();
  19742. // Observables
  19743. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19744. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19745. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19746. _this.onRestoreStateObservable = new BABYLON.Observable();
  19747. // Cache
  19748. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19749. _this._projectionMatrix = new BABYLON.Matrix();
  19750. _this._doNotComputeProjectionMatrix = false;
  19751. _this._postProcesses = new Array();
  19752. _this._transformMatrix = BABYLON.Matrix.Zero();
  19753. _this._activeMeshes = new BABYLON.SmartArray(256);
  19754. _this._globalPosition = BABYLON.Vector3.Zero();
  19755. _this._refreshFrustumPlanes = true;
  19756. _this.getScene().addCamera(_this);
  19757. if (!_this.getScene().activeCamera) {
  19758. _this.getScene().activeCamera = _this;
  19759. }
  19760. _this.position = position;
  19761. return _this;
  19762. }
  19763. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19764. get: function () {
  19765. return Camera._PERSPECTIVE_CAMERA;
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19771. get: function () {
  19772. return Camera._ORTHOGRAPHIC_CAMERA;
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19778. /**
  19779. * This is the default FOV mode for perspective cameras.
  19780. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19781. *
  19782. */
  19783. get: function () {
  19784. return Camera._FOVMODE_VERTICAL_FIXED;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19790. /**
  19791. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19792. *
  19793. */
  19794. get: function () {
  19795. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19801. get: function () {
  19802. return Camera._RIG_MODE_NONE;
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19808. get: function () {
  19809. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19815. get: function () {
  19816. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19822. get: function () {
  19823. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19829. get: function () {
  19830. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19836. get: function () {
  19837. return Camera._RIG_MODE_VR;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19843. get: function () {
  19844. return Camera._RIG_MODE_WEBVR;
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. /**
  19850. * Store current camera state (fov, position, etc..)
  19851. */
  19852. Camera.prototype.storeState = function () {
  19853. this._stateStored = true;
  19854. this._storedFov = this.fov;
  19855. return this;
  19856. };
  19857. /**
  19858. * Restores the camera state values if it has been stored. You must call storeState() first
  19859. */
  19860. Camera.prototype._restoreStateValues = function () {
  19861. if (!this._stateStored) {
  19862. return false;
  19863. }
  19864. this.fov = this._storedFov;
  19865. return true;
  19866. };
  19867. /**
  19868. * Restored camera state. You must call storeState() first
  19869. */
  19870. Camera.prototype.restoreState = function () {
  19871. if (this._restoreStateValues()) {
  19872. this.onRestoreStateObservable.notifyObservers(this);
  19873. return true;
  19874. }
  19875. return false;
  19876. };
  19877. Camera.prototype.getClassName = function () {
  19878. return "Camera";
  19879. };
  19880. /**
  19881. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19882. */
  19883. Camera.prototype.toString = function (fullDetails) {
  19884. var ret = "Name: " + this.name;
  19885. ret += ", type: " + this.getClassName();
  19886. if (this.animations) {
  19887. for (var i = 0; i < this.animations.length; i++) {
  19888. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19889. }
  19890. }
  19891. if (fullDetails) {
  19892. }
  19893. return ret;
  19894. };
  19895. Object.defineProperty(Camera.prototype, "globalPosition", {
  19896. get: function () {
  19897. return this._globalPosition;
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Camera.prototype.getActiveMeshes = function () {
  19903. return this._activeMeshes;
  19904. };
  19905. Camera.prototype.isActiveMesh = function (mesh) {
  19906. return (this._activeMeshes.indexOf(mesh) !== -1);
  19907. };
  19908. //Cache
  19909. Camera.prototype._initCache = function () {
  19910. _super.prototype._initCache.call(this);
  19911. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19912. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19913. this._cache.mode = undefined;
  19914. this._cache.minZ = undefined;
  19915. this._cache.maxZ = undefined;
  19916. this._cache.fov = undefined;
  19917. this._cache.fovMode = undefined;
  19918. this._cache.aspectRatio = undefined;
  19919. this._cache.orthoLeft = undefined;
  19920. this._cache.orthoRight = undefined;
  19921. this._cache.orthoBottom = undefined;
  19922. this._cache.orthoTop = undefined;
  19923. this._cache.renderWidth = undefined;
  19924. this._cache.renderHeight = undefined;
  19925. };
  19926. Camera.prototype._updateCache = function (ignoreParentClass) {
  19927. if (!ignoreParentClass) {
  19928. _super.prototype._updateCache.call(this);
  19929. }
  19930. this._cache.position.copyFrom(this.position);
  19931. this._cache.upVector.copyFrom(this.upVector);
  19932. };
  19933. // Synchronized
  19934. Camera.prototype._isSynchronized = function () {
  19935. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19936. };
  19937. Camera.prototype._isSynchronizedViewMatrix = function () {
  19938. if (!_super.prototype._isSynchronized.call(this))
  19939. return false;
  19940. return this._cache.position.equals(this.position)
  19941. && this._cache.upVector.equals(this.upVector)
  19942. && this.isSynchronizedWithParent();
  19943. };
  19944. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19945. var check = this._cache.mode === this.mode
  19946. && this._cache.minZ === this.minZ
  19947. && this._cache.maxZ === this.maxZ;
  19948. if (!check) {
  19949. return false;
  19950. }
  19951. var engine = this.getEngine();
  19952. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19953. check = this._cache.fov === this.fov
  19954. && this._cache.fovMode === this.fovMode
  19955. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19956. }
  19957. else {
  19958. check = this._cache.orthoLeft === this.orthoLeft
  19959. && this._cache.orthoRight === this.orthoRight
  19960. && this._cache.orthoBottom === this.orthoBottom
  19961. && this._cache.orthoTop === this.orthoTop
  19962. && this._cache.renderWidth === engine.getRenderWidth()
  19963. && this._cache.renderHeight === engine.getRenderHeight();
  19964. }
  19965. return check;
  19966. };
  19967. // Controls
  19968. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19969. };
  19970. Camera.prototype.detachControl = function (element) {
  19971. };
  19972. Camera.prototype.update = function () {
  19973. this._checkInputs();
  19974. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19975. this._updateRigCameras();
  19976. }
  19977. };
  19978. Camera.prototype._checkInputs = function () {
  19979. this.onAfterCheckInputsObservable.notifyObservers(this);
  19980. };
  19981. Object.defineProperty(Camera.prototype, "rigCameras", {
  19982. get: function () {
  19983. return this._rigCameras;
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19989. get: function () {
  19990. return this._rigPostProcess;
  19991. },
  19992. enumerable: true,
  19993. configurable: true
  19994. });
  19995. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19996. // invalidate framebuffer
  19997. if (this._postProcesses.length > 0) {
  19998. this._postProcesses[0].markTextureDirty();
  19999. }
  20000. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20001. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20002. var cam = this._rigCameras[i];
  20003. var rigPostProcess = cam._rigPostProcess;
  20004. // for VR rig, there does not have to be a post process
  20005. if (rigPostProcess) {
  20006. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20007. if (isPass) {
  20008. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20009. cam.isIntermediate = this._postProcesses.length === 0;
  20010. }
  20011. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20012. rigPostProcess.markTextureDirty();
  20013. }
  20014. else {
  20015. cam._postProcesses = this._postProcesses.slice(0);
  20016. }
  20017. }
  20018. };
  20019. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20020. if (insertAt === void 0) { insertAt = null; }
  20021. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20022. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20023. return 0;
  20024. }
  20025. if (insertAt == null || insertAt < 0) {
  20026. this._postProcesses.push(postProcess);
  20027. }
  20028. else {
  20029. this._postProcesses.splice(insertAt, 0, postProcess);
  20030. }
  20031. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20032. return this._postProcesses.indexOf(postProcess);
  20033. };
  20034. Camera.prototype.detachPostProcess = function (postProcess) {
  20035. var idx = this._postProcesses.indexOf(postProcess);
  20036. if (idx !== -1) {
  20037. this._postProcesses.splice(idx, 1);
  20038. }
  20039. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20040. };
  20041. Camera.prototype.getWorldMatrix = function () {
  20042. if (!this._worldMatrix) {
  20043. this._worldMatrix = BABYLON.Matrix.Identity();
  20044. }
  20045. var viewMatrix = this.getViewMatrix();
  20046. viewMatrix.invertToRef(this._worldMatrix);
  20047. return this._worldMatrix;
  20048. };
  20049. Camera.prototype._getViewMatrix = function () {
  20050. return BABYLON.Matrix.Identity();
  20051. };
  20052. Camera.prototype.getViewMatrix = function (force) {
  20053. if (!force && this._isSynchronizedViewMatrix()) {
  20054. return this._computedViewMatrix;
  20055. }
  20056. this.updateCache();
  20057. this._computedViewMatrix = this._getViewMatrix();
  20058. this._currentRenderId = this.getScene().getRenderId();
  20059. this._refreshFrustumPlanes = true;
  20060. if (!this.parent || !this.parent.getWorldMatrix) {
  20061. this._globalPosition.copyFrom(this.position);
  20062. }
  20063. else {
  20064. if (!this._worldMatrix) {
  20065. this._worldMatrix = BABYLON.Matrix.Identity();
  20066. }
  20067. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20068. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20069. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20070. this._computedViewMatrix.invert();
  20071. this._markSyncedWithParent();
  20072. }
  20073. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20074. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20075. }
  20076. this.onViewMatrixChangedObservable.notifyObservers(this);
  20077. return this._computedViewMatrix;
  20078. };
  20079. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20080. this._doNotComputeProjectionMatrix = true;
  20081. if (projection !== undefined) {
  20082. this._projectionMatrix = projection;
  20083. }
  20084. };
  20085. ;
  20086. Camera.prototype.unfreezeProjectionMatrix = function () {
  20087. this._doNotComputeProjectionMatrix = false;
  20088. };
  20089. ;
  20090. Camera.prototype.getProjectionMatrix = function (force) {
  20091. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20092. return this._projectionMatrix;
  20093. }
  20094. // Cache
  20095. this._cache.mode = this.mode;
  20096. this._cache.minZ = this.minZ;
  20097. this._cache.maxZ = this.maxZ;
  20098. // Matrix
  20099. this._refreshFrustumPlanes = true;
  20100. var engine = this.getEngine();
  20101. var scene = this.getScene();
  20102. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20103. this._cache.fov = this.fov;
  20104. this._cache.fovMode = this.fovMode;
  20105. this._cache.aspectRatio = engine.getAspectRatio(this);
  20106. if (this.minZ <= 0) {
  20107. this.minZ = 0.1;
  20108. }
  20109. if (scene.useRightHandedSystem) {
  20110. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20111. }
  20112. else {
  20113. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20114. }
  20115. }
  20116. else {
  20117. var halfWidth = engine.getRenderWidth() / 2.0;
  20118. var halfHeight = engine.getRenderHeight() / 2.0;
  20119. if (scene.useRightHandedSystem) {
  20120. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20121. }
  20122. else {
  20123. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20124. }
  20125. this._cache.orthoLeft = this.orthoLeft;
  20126. this._cache.orthoRight = this.orthoRight;
  20127. this._cache.orthoBottom = this.orthoBottom;
  20128. this._cache.orthoTop = this.orthoTop;
  20129. this._cache.renderWidth = engine.getRenderWidth();
  20130. this._cache.renderHeight = engine.getRenderHeight();
  20131. }
  20132. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20133. return this._projectionMatrix;
  20134. };
  20135. Camera.prototype.getTranformationMatrix = function () {
  20136. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20137. return this._transformMatrix;
  20138. };
  20139. Camera.prototype.updateFrustumPlanes = function () {
  20140. if (!this._refreshFrustumPlanes) {
  20141. return;
  20142. }
  20143. this.getTranformationMatrix();
  20144. if (!this._frustumPlanes) {
  20145. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20146. }
  20147. else {
  20148. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20149. }
  20150. this._refreshFrustumPlanes = false;
  20151. };
  20152. Camera.prototype.isInFrustum = function (target) {
  20153. this.updateFrustumPlanes();
  20154. return target.isInFrustum(this._frustumPlanes);
  20155. };
  20156. Camera.prototype.isCompletelyInFrustum = function (target) {
  20157. this.updateFrustumPlanes();
  20158. return target.isCompletelyInFrustum(this._frustumPlanes);
  20159. };
  20160. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20161. if (length === void 0) { length = 100; }
  20162. if (!transform) {
  20163. transform = this.getWorldMatrix();
  20164. }
  20165. if (!origin) {
  20166. origin = this.position;
  20167. }
  20168. var forward = new BABYLON.Vector3(0, 0, 1);
  20169. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20170. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20171. return new BABYLON.Ray(origin, direction, length);
  20172. };
  20173. /**
  20174. * Releases resources associated with this node.
  20175. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20176. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20177. */
  20178. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20179. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20180. // Observables
  20181. this.onViewMatrixChangedObservable.clear();
  20182. this.onProjectionMatrixChangedObservable.clear();
  20183. this.onAfterCheckInputsObservable.clear();
  20184. this.onRestoreStateObservable.clear();
  20185. // Inputs
  20186. if (this.inputs) {
  20187. this.inputs.clear();
  20188. }
  20189. // Animations
  20190. this.getScene().stopAnimation(this);
  20191. // Remove from scene
  20192. this.getScene().removeCamera(this);
  20193. while (this._rigCameras.length > 0) {
  20194. var camera = this._rigCameras.pop();
  20195. if (camera) {
  20196. camera.dispose();
  20197. }
  20198. }
  20199. // Postprocesses
  20200. if (this._rigPostProcess) {
  20201. this._rigPostProcess.dispose(this);
  20202. this._rigPostProcess = null;
  20203. this._postProcesses = [];
  20204. }
  20205. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20206. this._rigPostProcess = null;
  20207. this._postProcesses = [];
  20208. }
  20209. else {
  20210. var i = this._postProcesses.length;
  20211. while (--i >= 0) {
  20212. this._postProcesses[i].dispose(this);
  20213. }
  20214. }
  20215. // Render targets
  20216. var i = this.customRenderTargets.length;
  20217. while (--i >= 0) {
  20218. this.customRenderTargets[i].dispose();
  20219. }
  20220. this.customRenderTargets = [];
  20221. // Active Meshes
  20222. this._activeMeshes.dispose();
  20223. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20224. };
  20225. Object.defineProperty(Camera.prototype, "leftCamera", {
  20226. // ---- Camera rigs section ----
  20227. get: function () {
  20228. if (this._rigCameras.length < 1) {
  20229. return null;
  20230. }
  20231. return this._rigCameras[0];
  20232. },
  20233. enumerable: true,
  20234. configurable: true
  20235. });
  20236. Object.defineProperty(Camera.prototype, "rightCamera", {
  20237. get: function () {
  20238. if (this._rigCameras.length < 2) {
  20239. return null;
  20240. }
  20241. return this._rigCameras[1];
  20242. },
  20243. enumerable: true,
  20244. configurable: true
  20245. });
  20246. Camera.prototype.getLeftTarget = function () {
  20247. if (this._rigCameras.length < 1) {
  20248. return null;
  20249. }
  20250. return this._rigCameras[0].getTarget();
  20251. };
  20252. Camera.prototype.getRightTarget = function () {
  20253. if (this._rigCameras.length < 2) {
  20254. return null;
  20255. }
  20256. return this._rigCameras[1].getTarget();
  20257. };
  20258. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20259. if (this.cameraRigMode === mode) {
  20260. return;
  20261. }
  20262. while (this._rigCameras.length > 0) {
  20263. var camera = this._rigCameras.pop();
  20264. if (camera) {
  20265. camera.dispose();
  20266. }
  20267. }
  20268. this.cameraRigMode = mode;
  20269. this._cameraRigParams = {};
  20270. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20271. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20272. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20273. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20274. // create the rig cameras, unless none
  20275. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20276. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20277. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20278. if (leftCamera && rightCamera) {
  20279. this._rigCameras.push(leftCamera);
  20280. this._rigCameras.push(rightCamera);
  20281. }
  20282. }
  20283. switch (this.cameraRigMode) {
  20284. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20285. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20286. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20287. break;
  20288. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20289. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20290. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20291. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20292. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20293. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20294. break;
  20295. case Camera.RIG_MODE_VR:
  20296. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20297. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20298. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20299. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20300. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20301. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20302. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20303. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20304. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20305. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20306. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20307. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20308. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20309. if (metrics.compensateDistortion) {
  20310. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20311. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20312. }
  20313. break;
  20314. case Camera.RIG_MODE_WEBVR:
  20315. if (rigParams.vrDisplay) {
  20316. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20317. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20318. //Left eye
  20319. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20320. this._rigCameras[0].setCameraRigParameter("left", true);
  20321. //leaving this for future reference
  20322. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20323. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20324. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20325. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20326. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20327. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20328. this._rigCameras[0].parent = this;
  20329. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20330. //Right eye
  20331. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20332. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20333. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20334. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20335. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20336. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20337. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20338. this._rigCameras[1].parent = this;
  20339. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20340. if (Camera.UseAlternateWebVRRendering) {
  20341. this._rigCameras[1]._skipRendering = true;
  20342. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20343. }
  20344. }
  20345. break;
  20346. }
  20347. this._cascadePostProcessesToRigCams();
  20348. this.update();
  20349. };
  20350. Camera.prototype._getVRProjectionMatrix = function () {
  20351. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20352. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20353. return this._projectionMatrix;
  20354. };
  20355. Camera.prototype._updateCameraRotationMatrix = function () {
  20356. //Here for WebVR
  20357. };
  20358. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20359. //Here for WebVR
  20360. };
  20361. /**
  20362. * This function MUST be overwritten by the different WebVR cameras available.
  20363. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20364. */
  20365. Camera.prototype._getWebVRProjectionMatrix = function () {
  20366. return BABYLON.Matrix.Identity();
  20367. };
  20368. /**
  20369. * This function MUST be overwritten by the different WebVR cameras available.
  20370. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20371. */
  20372. Camera.prototype._getWebVRViewMatrix = function () {
  20373. return BABYLON.Matrix.Identity();
  20374. };
  20375. Camera.prototype.setCameraRigParameter = function (name, value) {
  20376. if (!this._cameraRigParams) {
  20377. this._cameraRigParams = {};
  20378. }
  20379. this._cameraRigParams[name] = value;
  20380. //provisionnally:
  20381. if (name === "interaxialDistance") {
  20382. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20383. }
  20384. };
  20385. /**
  20386. * needs to be overridden by children so sub has required properties to be copied
  20387. */
  20388. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20389. return null;
  20390. };
  20391. /**
  20392. * May need to be overridden by children
  20393. */
  20394. Camera.prototype._updateRigCameras = function () {
  20395. for (var i = 0; i < this._rigCameras.length; i++) {
  20396. this._rigCameras[i].minZ = this.minZ;
  20397. this._rigCameras[i].maxZ = this.maxZ;
  20398. this._rigCameras[i].fov = this.fov;
  20399. }
  20400. // only update viewport when ANAGLYPH
  20401. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20402. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20403. }
  20404. };
  20405. Camera.prototype._setupInputs = function () {
  20406. };
  20407. Camera.prototype.serialize = function () {
  20408. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20409. // Type
  20410. serializationObject.type = this.getClassName();
  20411. // Parent
  20412. if (this.parent) {
  20413. serializationObject.parentId = this.parent.id;
  20414. }
  20415. if (this.inputs) {
  20416. this.inputs.serialize(serializationObject);
  20417. }
  20418. // Animations
  20419. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20420. serializationObject.ranges = this.serializeAnimationRanges();
  20421. return serializationObject;
  20422. };
  20423. Camera.prototype.clone = function (name) {
  20424. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20425. };
  20426. Camera.prototype.getDirection = function (localAxis) {
  20427. var result = BABYLON.Vector3.Zero();
  20428. this.getDirectionToRef(localAxis, result);
  20429. return result;
  20430. };
  20431. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20432. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20433. };
  20434. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20435. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20436. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20437. switch (type) {
  20438. case "ArcRotateCamera":
  20439. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20440. case "DeviceOrientationCamera":
  20441. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20442. case "FollowCamera":
  20443. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20444. case "ArcFollowCamera":
  20445. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20446. case "GamepadCamera":
  20447. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20448. case "TouchCamera":
  20449. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20450. case "VirtualJoysticksCamera":
  20451. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20452. case "WebVRFreeCamera":
  20453. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20454. case "WebVRGamepadCamera":
  20455. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20456. case "VRDeviceOrientationFreeCamera":
  20457. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20458. case "VRDeviceOrientationGamepadCamera":
  20459. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20460. case "AnaglyphArcRotateCamera":
  20461. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20462. case "AnaglyphFreeCamera":
  20463. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20464. case "AnaglyphGamepadCamera":
  20465. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20466. case "AnaglyphUniversalCamera":
  20467. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20468. case "StereoscopicArcRotateCamera":
  20469. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20470. case "StereoscopicFreeCamera":
  20471. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20472. case "StereoscopicGamepadCamera":
  20473. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20474. case "StereoscopicUniversalCamera":
  20475. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20476. case "FreeCamera":// Forcing Universal here
  20477. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20478. default:// Universal Camera is the default value
  20479. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20480. }
  20481. };
  20482. Camera.prototype.computeWorldMatrix = function () {
  20483. return this.getWorldMatrix();
  20484. };
  20485. Camera.Parse = function (parsedCamera, scene) {
  20486. var type = parsedCamera.type;
  20487. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20488. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20489. // Parent
  20490. if (parsedCamera.parentId) {
  20491. camera._waitingParentId = parsedCamera.parentId;
  20492. }
  20493. //If camera has an input manager, let it parse inputs settings
  20494. if (camera.inputs) {
  20495. camera.inputs.parse(parsedCamera);
  20496. camera._setupInputs();
  20497. }
  20498. if (camera.setPosition) {
  20499. camera.position.copyFromFloats(0, 0, 0);
  20500. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20501. }
  20502. // Target
  20503. if (parsedCamera.target) {
  20504. if (camera.setTarget) {
  20505. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20506. }
  20507. }
  20508. // Apply 3d rig, when found
  20509. if (parsedCamera.cameraRigMode) {
  20510. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20511. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20512. }
  20513. // Animations
  20514. if (parsedCamera.animations) {
  20515. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20516. var parsedAnimation = parsedCamera.animations[animationIndex];
  20517. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20518. }
  20519. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20520. }
  20521. if (parsedCamera.autoAnimate) {
  20522. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20523. }
  20524. return camera;
  20525. };
  20526. // Statics
  20527. Camera._PERSPECTIVE_CAMERA = 0;
  20528. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20529. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20530. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20531. Camera._RIG_MODE_NONE = 0;
  20532. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20533. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20534. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20535. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20536. Camera._RIG_MODE_VR = 20;
  20537. Camera._RIG_MODE_WEBVR = 21;
  20538. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20539. Camera.UseAlternateWebVRRendering = false;
  20540. __decorate([
  20541. BABYLON.serializeAsVector3()
  20542. ], Camera.prototype, "position", void 0);
  20543. __decorate([
  20544. BABYLON.serializeAsVector3()
  20545. ], Camera.prototype, "upVector", void 0);
  20546. __decorate([
  20547. BABYLON.serialize()
  20548. ], Camera.prototype, "orthoLeft", void 0);
  20549. __decorate([
  20550. BABYLON.serialize()
  20551. ], Camera.prototype, "orthoRight", void 0);
  20552. __decorate([
  20553. BABYLON.serialize()
  20554. ], Camera.prototype, "orthoBottom", void 0);
  20555. __decorate([
  20556. BABYLON.serialize()
  20557. ], Camera.prototype, "orthoTop", void 0);
  20558. __decorate([
  20559. BABYLON.serialize()
  20560. ], Camera.prototype, "fov", void 0);
  20561. __decorate([
  20562. BABYLON.serialize()
  20563. ], Camera.prototype, "minZ", void 0);
  20564. __decorate([
  20565. BABYLON.serialize()
  20566. ], Camera.prototype, "maxZ", void 0);
  20567. __decorate([
  20568. BABYLON.serialize()
  20569. ], Camera.prototype, "inertia", void 0);
  20570. __decorate([
  20571. BABYLON.serialize()
  20572. ], Camera.prototype, "mode", void 0);
  20573. __decorate([
  20574. BABYLON.serialize()
  20575. ], Camera.prototype, "layerMask", void 0);
  20576. __decorate([
  20577. BABYLON.serialize()
  20578. ], Camera.prototype, "fovMode", void 0);
  20579. __decorate([
  20580. BABYLON.serialize()
  20581. ], Camera.prototype, "cameraRigMode", void 0);
  20582. __decorate([
  20583. BABYLON.serialize()
  20584. ], Camera.prototype, "interaxialDistance", void 0);
  20585. __decorate([
  20586. BABYLON.serialize()
  20587. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20588. return Camera;
  20589. }(BABYLON.Node));
  20590. BABYLON.Camera = Camera;
  20591. })(BABYLON || (BABYLON = {}));
  20592. //# sourceMappingURL=babylon.camera.js.map
  20593. var BABYLON;
  20594. (function (BABYLON) {
  20595. var RenderingManager = /** @class */ (function () {
  20596. function RenderingManager(scene) {
  20597. this._renderingGroups = new Array();
  20598. this._autoClearDepthStencil = {};
  20599. this._customOpaqueSortCompareFn = {};
  20600. this._customAlphaTestSortCompareFn = {};
  20601. this._customTransparentSortCompareFn = {};
  20602. this._renderinGroupInfo = null;
  20603. this._scene = scene;
  20604. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20605. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20606. }
  20607. }
  20608. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20609. if (depth === void 0) { depth = true; }
  20610. if (stencil === void 0) { stencil = true; }
  20611. if (this._depthStencilBufferAlreadyCleaned) {
  20612. return;
  20613. }
  20614. this._scene.getEngine().clear(null, false, depth, stencil);
  20615. this._depthStencilBufferAlreadyCleaned = true;
  20616. };
  20617. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20618. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20619. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20620. var info = null;
  20621. if (observable) {
  20622. if (!this._renderinGroupInfo) {
  20623. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20624. }
  20625. info = this._renderinGroupInfo;
  20626. info.scene = this._scene;
  20627. info.camera = this._scene.activeCamera;
  20628. }
  20629. // Dispatch sprites
  20630. if (renderSprites) {
  20631. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20632. var manager = this._scene.spriteManagers[index];
  20633. this.dispatchSprites(manager);
  20634. }
  20635. }
  20636. // Render
  20637. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20638. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20639. var renderingGroup = this._renderingGroups[index];
  20640. if (!renderingGroup && !observable)
  20641. continue;
  20642. var renderingGroupMask = 0;
  20643. // Fire PRECLEAR stage
  20644. if (observable && info) {
  20645. renderingGroupMask = Math.pow(2, index);
  20646. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20647. info.renderingGroupId = index;
  20648. observable.notifyObservers(info, renderingGroupMask);
  20649. }
  20650. // Clear depth/stencil if needed
  20651. if (RenderingManager.AUTOCLEAR) {
  20652. var autoClear = this._autoClearDepthStencil[index];
  20653. if (autoClear && autoClear.autoClear) {
  20654. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20655. }
  20656. }
  20657. if (observable && info) {
  20658. // Fire PREOPAQUE stage
  20659. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20660. observable.notifyObservers(info, renderingGroupMask);
  20661. // Fire PRETRANSPARENT stage
  20662. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20663. observable.notifyObservers(info, renderingGroupMask);
  20664. }
  20665. if (renderingGroup)
  20666. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20667. // Fire POSTTRANSPARENT stage
  20668. if (observable && info) {
  20669. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20670. observable.notifyObservers(info, renderingGroupMask);
  20671. }
  20672. }
  20673. };
  20674. RenderingManager.prototype.reset = function () {
  20675. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20676. var renderingGroup = this._renderingGroups[index];
  20677. if (renderingGroup) {
  20678. renderingGroup.prepare();
  20679. }
  20680. }
  20681. };
  20682. RenderingManager.prototype.dispose = function () {
  20683. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20684. var renderingGroup = this._renderingGroups[index];
  20685. if (renderingGroup) {
  20686. renderingGroup.dispose();
  20687. }
  20688. }
  20689. this._renderingGroups.length = 0;
  20690. };
  20691. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20692. if (this._renderingGroups[renderingGroupId] === undefined) {
  20693. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20694. }
  20695. };
  20696. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20697. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20698. this._prepareRenderingGroup(renderingGroupId);
  20699. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20700. };
  20701. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20702. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20703. this._prepareRenderingGroup(renderingGroupId);
  20704. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20705. };
  20706. /**
  20707. * @param subMesh The submesh to dispatch
  20708. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20709. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20710. */
  20711. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20712. if (mesh === undefined) {
  20713. mesh = subMesh.getMesh();
  20714. }
  20715. var renderingGroupId = mesh.renderingGroupId || 0;
  20716. this._prepareRenderingGroup(renderingGroupId);
  20717. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20718. };
  20719. /**
  20720. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20721. * This allowed control for front to back rendering or reversly depending of the special needs.
  20722. *
  20723. * @param renderingGroupId The rendering group id corresponding to its index
  20724. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20725. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20726. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20727. */
  20728. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20729. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20730. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20731. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20732. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20733. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20734. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20735. if (this._renderingGroups[renderingGroupId]) {
  20736. var group = this._renderingGroups[renderingGroupId];
  20737. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20738. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20739. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20740. }
  20741. };
  20742. /**
  20743. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20744. *
  20745. * @param renderingGroupId The rendering group id corresponding to its index
  20746. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20747. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20748. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20749. */
  20750. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20751. if (depth === void 0) { depth = true; }
  20752. if (stencil === void 0) { stencil = true; }
  20753. this._autoClearDepthStencil[renderingGroupId] = {
  20754. autoClear: autoClearDepthStencil,
  20755. depth: depth,
  20756. stencil: stencil
  20757. };
  20758. };
  20759. /**
  20760. * The max id used for rendering groups (not included)
  20761. */
  20762. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20763. /**
  20764. * The min id used for rendering groups (included)
  20765. */
  20766. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20767. /**
  20768. * Used to globally prevent autoclearing scenes.
  20769. */
  20770. RenderingManager.AUTOCLEAR = true;
  20771. return RenderingManager;
  20772. }());
  20773. BABYLON.RenderingManager = RenderingManager;
  20774. })(BABYLON || (BABYLON = {}));
  20775. //# sourceMappingURL=babylon.renderingManager.js.map
  20776. var BABYLON;
  20777. (function (BABYLON) {
  20778. var RenderingGroup = /** @class */ (function () {
  20779. /**
  20780. * Creates a new rendering group.
  20781. * @param index The rendering group index
  20782. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20783. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20784. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20785. */
  20786. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20787. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20788. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20789. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20790. this.index = index;
  20791. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20792. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20793. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20794. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20795. this._particleSystems = new BABYLON.SmartArray(256);
  20796. this._spriteManagers = new BABYLON.SmartArray(256);
  20797. this._edgesRenderers = new BABYLON.SmartArray(16);
  20798. this._scene = scene;
  20799. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20800. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20801. this.transparentSortCompareFn = transparentSortCompareFn;
  20802. }
  20803. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20804. /**
  20805. * Set the opaque sort comparison function.
  20806. * If null the sub meshes will be render in the order they were created
  20807. */
  20808. set: function (value) {
  20809. this._opaqueSortCompareFn = value;
  20810. if (value) {
  20811. this._renderOpaque = this.renderOpaqueSorted;
  20812. }
  20813. else {
  20814. this._renderOpaque = RenderingGroup.renderUnsorted;
  20815. }
  20816. },
  20817. enumerable: true,
  20818. configurable: true
  20819. });
  20820. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20821. /**
  20822. * Set the alpha test sort comparison function.
  20823. * If null the sub meshes will be render in the order they were created
  20824. */
  20825. set: function (value) {
  20826. this._alphaTestSortCompareFn = value;
  20827. if (value) {
  20828. this._renderAlphaTest = this.renderAlphaTestSorted;
  20829. }
  20830. else {
  20831. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20832. }
  20833. },
  20834. enumerable: true,
  20835. configurable: true
  20836. });
  20837. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20838. /**
  20839. * Set the transparent sort comparison function.
  20840. * If null the sub meshes will be render in the order they were created
  20841. */
  20842. set: function (value) {
  20843. if (value) {
  20844. this._transparentSortCompareFn = value;
  20845. }
  20846. else {
  20847. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20848. }
  20849. this._renderTransparent = this.renderTransparentSorted;
  20850. },
  20851. enumerable: true,
  20852. configurable: true
  20853. });
  20854. /**
  20855. * Render all the sub meshes contained in the group.
  20856. * @param customRenderFunction Used to override the default render behaviour of the group.
  20857. * @returns true if rendered some submeshes.
  20858. */
  20859. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20860. if (customRenderFunction) {
  20861. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20862. return;
  20863. }
  20864. var engine = this._scene.getEngine();
  20865. // Depth only
  20866. if (this._depthOnlySubMeshes.length !== 0) {
  20867. engine.setColorWrite(false);
  20868. this._renderAlphaTest(this._depthOnlySubMeshes);
  20869. engine.setColorWrite(true);
  20870. }
  20871. // Opaque
  20872. if (this._opaqueSubMeshes.length !== 0) {
  20873. this._renderOpaque(this._opaqueSubMeshes);
  20874. }
  20875. // Alpha test
  20876. if (this._alphaTestSubMeshes.length !== 0) {
  20877. this._renderAlphaTest(this._alphaTestSubMeshes);
  20878. }
  20879. var stencilState = engine.getStencilBuffer();
  20880. engine.setStencilBuffer(false);
  20881. // Sprites
  20882. if (renderSprites) {
  20883. this._renderSprites();
  20884. }
  20885. // Particles
  20886. if (renderParticles) {
  20887. this._renderParticles(activeMeshes);
  20888. }
  20889. if (this.onBeforeTransparentRendering) {
  20890. this.onBeforeTransparentRendering();
  20891. }
  20892. // Transparent
  20893. if (this._transparentSubMeshes.length !== 0) {
  20894. this._renderTransparent(this._transparentSubMeshes);
  20895. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20896. }
  20897. // Set back stencil to false in case it changes before the edge renderer.
  20898. engine.setStencilBuffer(false);
  20899. // Edges
  20900. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20901. this._edgesRenderers.data[edgesRendererIndex].render();
  20902. }
  20903. // Restore Stencil state.
  20904. engine.setStencilBuffer(stencilState);
  20905. };
  20906. /**
  20907. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20908. * @param subMeshes The submeshes to render
  20909. */
  20910. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20911. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20912. };
  20913. /**
  20914. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20915. * @param subMeshes The submeshes to render
  20916. */
  20917. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20918. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20919. };
  20920. /**
  20921. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20922. * @param subMeshes The submeshes to render
  20923. */
  20924. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20925. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20926. };
  20927. /**
  20928. * Renders the submeshes in a specified order.
  20929. * @param subMeshes The submeshes to sort before render
  20930. * @param sortCompareFn The comparison function use to sort
  20931. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20932. * @param transparent Specifies to activate blending if true
  20933. */
  20934. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20935. var subIndex = 0;
  20936. var subMesh;
  20937. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20938. for (; subIndex < subMeshes.length; subIndex++) {
  20939. subMesh = subMeshes.data[subIndex];
  20940. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20941. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20942. }
  20943. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20944. if (sortCompareFn) {
  20945. sortedArray.sort(sortCompareFn);
  20946. }
  20947. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20948. subMesh = sortedArray[subIndex];
  20949. if (transparent) {
  20950. var material = subMesh.getMaterial();
  20951. if (material && material.needDepthPrePass) {
  20952. var engine = material.getScene().getEngine();
  20953. engine.setColorWrite(false);
  20954. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20955. subMesh.render(false);
  20956. engine.setColorWrite(true);
  20957. }
  20958. }
  20959. subMesh.render(transparent);
  20960. }
  20961. };
  20962. /**
  20963. * Renders the submeshes in the order they were dispatched (no sort applied).
  20964. * @param subMeshes The submeshes to render
  20965. */
  20966. RenderingGroup.renderUnsorted = function (subMeshes) {
  20967. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20968. var submesh = subMeshes.data[subIndex];
  20969. submesh.render(false);
  20970. }
  20971. };
  20972. /**
  20973. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20974. * are rendered back to front if in the same alpha index.
  20975. *
  20976. * @param a The first submesh
  20977. * @param b The second submesh
  20978. * @returns The result of the comparison
  20979. */
  20980. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20981. // Alpha index first
  20982. if (a._alphaIndex > b._alphaIndex) {
  20983. return 1;
  20984. }
  20985. if (a._alphaIndex < b._alphaIndex) {
  20986. return -1;
  20987. }
  20988. // Then distance to camera
  20989. return RenderingGroup.backToFrontSortCompare(a, b);
  20990. };
  20991. /**
  20992. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20993. * are rendered back to front.
  20994. *
  20995. * @param a The first submesh
  20996. * @param b The second submesh
  20997. * @returns The result of the comparison
  20998. */
  20999. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21000. // Then distance to camera
  21001. if (a._distanceToCamera < b._distanceToCamera) {
  21002. return 1;
  21003. }
  21004. if (a._distanceToCamera > b._distanceToCamera) {
  21005. return -1;
  21006. }
  21007. return 0;
  21008. };
  21009. /**
  21010. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21011. * are rendered front to back (prevent overdraw).
  21012. *
  21013. * @param a The first submesh
  21014. * @param b The second submesh
  21015. * @returns The result of the comparison
  21016. */
  21017. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21018. // Then distance to camera
  21019. if (a._distanceToCamera < b._distanceToCamera) {
  21020. return -1;
  21021. }
  21022. if (a._distanceToCamera > b._distanceToCamera) {
  21023. return 1;
  21024. }
  21025. return 0;
  21026. };
  21027. /**
  21028. * Resets the different lists of submeshes to prepare a new frame.
  21029. */
  21030. RenderingGroup.prototype.prepare = function () {
  21031. this._opaqueSubMeshes.reset();
  21032. this._transparentSubMeshes.reset();
  21033. this._alphaTestSubMeshes.reset();
  21034. this._depthOnlySubMeshes.reset();
  21035. this._particleSystems.reset();
  21036. this._spriteManagers.reset();
  21037. this._edgesRenderers.reset();
  21038. };
  21039. RenderingGroup.prototype.dispose = function () {
  21040. this._opaqueSubMeshes.dispose();
  21041. this._transparentSubMeshes.dispose();
  21042. this._alphaTestSubMeshes.dispose();
  21043. this._depthOnlySubMeshes.dispose();
  21044. this._particleSystems.dispose();
  21045. this._spriteManagers.dispose();
  21046. this._edgesRenderers.dispose();
  21047. };
  21048. /**
  21049. * Inserts the submesh in its correct queue depending on its material.
  21050. * @param subMesh The submesh to dispatch
  21051. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21052. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21053. */
  21054. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21055. // Get mesh and materials if not provided
  21056. if (mesh === undefined) {
  21057. mesh = subMesh.getMesh();
  21058. }
  21059. if (material === undefined) {
  21060. material = subMesh.getMaterial();
  21061. }
  21062. if (material === null || material === undefined) {
  21063. return;
  21064. }
  21065. if (material.needAlphaBlendingForMesh(mesh)) {
  21066. this._transparentSubMeshes.push(subMesh);
  21067. }
  21068. else if (material.needAlphaTesting()) {
  21069. if (material.needDepthPrePass) {
  21070. this._depthOnlySubMeshes.push(subMesh);
  21071. }
  21072. this._alphaTestSubMeshes.push(subMesh);
  21073. }
  21074. else {
  21075. if (material.needDepthPrePass) {
  21076. this._depthOnlySubMeshes.push(subMesh);
  21077. }
  21078. this._opaqueSubMeshes.push(subMesh); // Opaque
  21079. }
  21080. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21081. this._edgesRenderers.push(mesh._edgesRenderer);
  21082. }
  21083. };
  21084. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21085. this._spriteManagers.push(spriteManager);
  21086. };
  21087. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21088. this._particleSystems.push(particleSystem);
  21089. };
  21090. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21091. if (this._particleSystems.length === 0) {
  21092. return;
  21093. }
  21094. // Particles
  21095. var activeCamera = this._scene.activeCamera;
  21096. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21097. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21098. var particleSystem = this._particleSystems.data[particleIndex];
  21099. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21100. continue;
  21101. }
  21102. var emitter = particleSystem.emitter;
  21103. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21104. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21105. }
  21106. }
  21107. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21108. };
  21109. RenderingGroup.prototype._renderSprites = function () {
  21110. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21111. return;
  21112. }
  21113. // Sprites
  21114. var activeCamera = this._scene.activeCamera;
  21115. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21116. for (var id = 0; id < this._spriteManagers.length; id++) {
  21117. var spriteManager = this._spriteManagers.data[id];
  21118. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21119. spriteManager.render();
  21120. }
  21121. }
  21122. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21123. };
  21124. return RenderingGroup;
  21125. }());
  21126. BABYLON.RenderingGroup = RenderingGroup;
  21127. })(BABYLON || (BABYLON = {}));
  21128. //# sourceMappingURL=babylon.renderingGroup.js.map
  21129. var BABYLON;
  21130. (function (BABYLON) {
  21131. var ClickInfo = /** @class */ (function () {
  21132. function ClickInfo() {
  21133. this._singleClick = false;
  21134. this._doubleClick = false;
  21135. this._hasSwiped = false;
  21136. this._ignore = false;
  21137. }
  21138. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21139. get: function () {
  21140. return this._singleClick;
  21141. },
  21142. set: function (b) {
  21143. this._singleClick = b;
  21144. },
  21145. enumerable: true,
  21146. configurable: true
  21147. });
  21148. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21149. get: function () {
  21150. return this._doubleClick;
  21151. },
  21152. set: function (b) {
  21153. this._doubleClick = b;
  21154. },
  21155. enumerable: true,
  21156. configurable: true
  21157. });
  21158. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21159. get: function () {
  21160. return this._hasSwiped;
  21161. },
  21162. set: function (b) {
  21163. this._hasSwiped = b;
  21164. },
  21165. enumerable: true,
  21166. configurable: true
  21167. });
  21168. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21169. get: function () {
  21170. return this._ignore;
  21171. },
  21172. set: function (b) {
  21173. this._ignore = b;
  21174. },
  21175. enumerable: true,
  21176. configurable: true
  21177. });
  21178. return ClickInfo;
  21179. }());
  21180. /**
  21181. * This class is used by the onRenderingGroupObservable
  21182. */
  21183. var RenderingGroupInfo = /** @class */ (function () {
  21184. function RenderingGroupInfo() {
  21185. }
  21186. /**
  21187. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21188. * This stage will be fired no matter what
  21189. */
  21190. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21191. /**
  21192. * Called before opaque object are rendered.
  21193. * This stage will be fired only if there's 3D Opaque content to render
  21194. */
  21195. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21196. /**
  21197. * Called after the opaque objects are rendered and before the transparent ones
  21198. * This stage will be fired only if there's 3D transparent content to render
  21199. */
  21200. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21201. /**
  21202. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21203. * This stage will be fired no matter what
  21204. */
  21205. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21206. return RenderingGroupInfo;
  21207. }());
  21208. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21209. /**
  21210. * Represents a scene to be rendered by the engine.
  21211. * @see http://doc.babylonjs.com/page.php?p=21911
  21212. */
  21213. var Scene = /** @class */ (function () {
  21214. /**
  21215. * @constructor
  21216. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21217. */
  21218. function Scene(engine) {
  21219. // Members
  21220. this.autoClear = true;
  21221. this.autoClearDepthAndStencil = true;
  21222. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21223. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21224. this.forceWireframe = false;
  21225. this._forcePointsCloud = false;
  21226. this.forceShowBoundingBoxes = false;
  21227. this.animationsEnabled = true;
  21228. this.useConstantAnimationDeltaTime = false;
  21229. this.constantlyUpdateMeshUnderPointer = false;
  21230. this.hoverCursor = "pointer";
  21231. this.defaultCursor = "";
  21232. /**
  21233. * This is used to call preventDefault() on pointer down
  21234. * in order to block unwanted artifacts like system double clicks
  21235. */
  21236. this.preventDefaultOnPointerDown = true;
  21237. // Metadata
  21238. this.metadata = null;
  21239. /**
  21240. * An event triggered when the scene is disposed.
  21241. * @type {BABYLON.Observable}
  21242. */
  21243. this.onDisposeObservable = new BABYLON.Observable();
  21244. /**
  21245. * An event triggered before rendering the scene (right after animations and physics)
  21246. * @type {BABYLON.Observable}
  21247. */
  21248. this.onBeforeRenderObservable = new BABYLON.Observable();
  21249. /**
  21250. * An event triggered after rendering the scene
  21251. * @type {BABYLON.Observable}
  21252. */
  21253. this.onAfterRenderObservable = new BABYLON.Observable();
  21254. /**
  21255. * An event triggered before animating the scene
  21256. * @type {BABYLON.Observable}
  21257. */
  21258. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21259. /**
  21260. * An event triggered after animations processing
  21261. * @type {BABYLON.Observable}
  21262. */
  21263. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21264. /**
  21265. * An event triggered before draw calls are ready to be sent
  21266. * @type {BABYLON.Observable}
  21267. */
  21268. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21269. /**
  21270. * An event triggered after draw calls have been sent
  21271. * @type {BABYLON.Observable}
  21272. */
  21273. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21274. /**
  21275. * An event triggered when physic simulation is about to be run
  21276. * @type {BABYLON.Observable}
  21277. */
  21278. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21279. /**
  21280. * An event triggered when physic simulation has been done
  21281. * @type {BABYLON.Observable}
  21282. */
  21283. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21284. /**
  21285. * An event triggered when the scene is ready
  21286. * @type {BABYLON.Observable}
  21287. */
  21288. this.onReadyObservable = new BABYLON.Observable();
  21289. /**
  21290. * An event triggered before rendering a camera
  21291. * @type {BABYLON.Observable}
  21292. */
  21293. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21294. /**
  21295. * An event triggered after rendering a camera
  21296. * @type {BABYLON.Observable}
  21297. */
  21298. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21299. /**
  21300. * An event triggered when active meshes evaluation is about to start
  21301. * @type {BABYLON.Observable}
  21302. */
  21303. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21304. /**
  21305. * An event triggered when active meshes evaluation is done
  21306. * @type {BABYLON.Observable}
  21307. */
  21308. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21309. /**
  21310. * An event triggered when particles rendering is about to start
  21311. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21312. * @type {BABYLON.Observable}
  21313. */
  21314. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21315. /**
  21316. * An event triggered when particles rendering is done
  21317. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21318. * @type {BABYLON.Observable}
  21319. */
  21320. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21321. /**
  21322. * An event triggered when sprites rendering is about to start
  21323. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21324. * @type {BABYLON.Observable}
  21325. */
  21326. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21327. /**
  21328. * An event triggered when sprites rendering is done
  21329. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21330. * @type {BABYLON.Observable}
  21331. */
  21332. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21333. /**
  21334. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21335. * @type {BABYLON.Observable}
  21336. */
  21337. this.onDataLoadedObservable = new BABYLON.Observable();
  21338. /**
  21339. * An event triggered when a camera is created
  21340. * @type {BABYLON.Observable}
  21341. */
  21342. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21343. /**
  21344. * An event triggered when a camera is removed
  21345. * @type {BABYLON.Observable}
  21346. */
  21347. this.onCameraRemovedObservable = new BABYLON.Observable();
  21348. /**
  21349. * An event triggered when a light is created
  21350. * @type {BABYLON.Observable}
  21351. */
  21352. this.onNewLightAddedObservable = new BABYLON.Observable();
  21353. /**
  21354. * An event triggered when a light is removed
  21355. * @type {BABYLON.Observable}
  21356. */
  21357. this.onLightRemovedObservable = new BABYLON.Observable();
  21358. /**
  21359. * An event triggered when a geometry is created
  21360. * @type {BABYLON.Observable}
  21361. */
  21362. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21363. /**
  21364. * An event triggered when a geometry is removed
  21365. * @type {BABYLON.Observable}
  21366. */
  21367. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21368. /**
  21369. * An event triggered when a transform node is created
  21370. * @type {BABYLON.Observable}
  21371. */
  21372. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21373. /**
  21374. * An event triggered when a transform node is removed
  21375. * @type {BABYLON.Observable}
  21376. */
  21377. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21378. /**
  21379. * An event triggered when a mesh is created
  21380. * @type {BABYLON.Observable}
  21381. */
  21382. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21383. /**
  21384. * An event triggered when a mesh is removed
  21385. * @type {BABYLON.Observable}
  21386. */
  21387. this.onMeshRemovedObservable = new BABYLON.Observable();
  21388. /**
  21389. * An event triggered when render targets are about to be rendered
  21390. * Can happen multiple times per frame.
  21391. * @type {BABYLON.Observable}
  21392. */
  21393. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21394. /**
  21395. * An event triggered when render targets were rendered.
  21396. * Can happen multiple times per frame.
  21397. * @type {BABYLON.Observable}
  21398. */
  21399. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21400. /**
  21401. * An event triggered before calculating deterministic simulation step
  21402. * @type {BABYLON.Observable}
  21403. */
  21404. this.onBeforeStepObservable = new BABYLON.Observable();
  21405. /**
  21406. * An event triggered after calculating deterministic simulation step
  21407. * @type {BABYLON.Observable}
  21408. */
  21409. this.onAfterStepObservable = new BABYLON.Observable();
  21410. /**
  21411. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21412. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21413. * 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)
  21414. */
  21415. this.onRenderingGroupObservable = new BABYLON.Observable();
  21416. // Animations
  21417. this.animations = [];
  21418. /**
  21419. * 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).
  21420. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21421. */
  21422. this.onPrePointerObservable = new BABYLON.Observable();
  21423. /**
  21424. * Observable event triggered each time an input event is received from the rendering canvas
  21425. */
  21426. this.onPointerObservable = new BABYLON.Observable();
  21427. this._meshPickProceed = false;
  21428. this._currentPickResult = null;
  21429. this._previousPickResult = null;
  21430. this._totalPointersPressed = 0;
  21431. this._doubleClickOccured = false;
  21432. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21433. this.cameraToUseForPointers = null;
  21434. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21435. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21436. this._startingPointerTime = 0;
  21437. this._previousStartingPointerTime = 0;
  21438. // Deterministic lockstep
  21439. this._timeAccumulator = 0;
  21440. this._currentStepId = 0;
  21441. this._currentInternalStep = 0;
  21442. // Keyboard
  21443. /**
  21444. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21445. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21446. */
  21447. this.onPreKeyboardObservable = new BABYLON.Observable();
  21448. /**
  21449. * Observable event triggered each time an keyboard event is received from the hosting window
  21450. */
  21451. this.onKeyboardObservable = new BABYLON.Observable();
  21452. // Coordinate system
  21453. /**
  21454. * use right-handed coordinate system on this scene.
  21455. * @type {boolean}
  21456. */
  21457. this._useRightHandedSystem = false;
  21458. // Fog
  21459. this._fogEnabled = true;
  21460. this._fogMode = Scene.FOGMODE_NONE;
  21461. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21462. this.fogDensity = 0.1;
  21463. this.fogStart = 0;
  21464. this.fogEnd = 1000.0;
  21465. // Lights
  21466. /**
  21467. * is shadow enabled on this scene.
  21468. * @type {boolean}
  21469. */
  21470. this._shadowsEnabled = true;
  21471. /**
  21472. * is light enabled on this scene.
  21473. * @type {boolean}
  21474. */
  21475. this._lightsEnabled = true;
  21476. /**
  21477. * All of the lights added to this scene.
  21478. * @see BABYLON.Light
  21479. * @type {BABYLON.Light[]}
  21480. */
  21481. this.lights = new Array();
  21482. // Cameras
  21483. /** All of the cameras added to this scene. */
  21484. this.cameras = new Array();
  21485. /** All of the active cameras added to this scene. */
  21486. this.activeCameras = new Array();
  21487. // Meshes
  21488. /**
  21489. * All of the tranform nodes added to this scene.
  21490. * @see BABYLON.TransformNode
  21491. * @type {BABYLON.TransformNode[]}
  21492. */
  21493. this.transformNodes = new Array();
  21494. /**
  21495. * All of the (abstract) meshes added to this scene.
  21496. * @see BABYLON.AbstractMesh
  21497. * @type {BABYLON.AbstractMesh[]}
  21498. */
  21499. this.meshes = new Array();
  21500. /**
  21501. * All of the animation groups added to this scene.
  21502. * @see BABYLON.AnimationGroup
  21503. * @type {BABYLON.AnimationGroup[]}
  21504. */
  21505. this.animationGroups = new Array();
  21506. // Geometries
  21507. this._geometries = new Array();
  21508. this.materials = new Array();
  21509. this.multiMaterials = new Array();
  21510. // Textures
  21511. this._texturesEnabled = true;
  21512. this.textures = new Array();
  21513. // Particles
  21514. this.particlesEnabled = true;
  21515. this.particleSystems = new Array();
  21516. // Sprites
  21517. this.spritesEnabled = true;
  21518. this.spriteManagers = new Array();
  21519. /**
  21520. * The list of layers (background and foreground) of the scene.
  21521. */
  21522. this.layers = new Array();
  21523. /**
  21524. * The list of effect layers (highlights/glow) contained in the scene.
  21525. */
  21526. this.effectLayers = new Array();
  21527. // Skeletons
  21528. this._skeletonsEnabled = true;
  21529. this.skeletons = new Array();
  21530. // Morph targets
  21531. this.morphTargetManagers = new Array();
  21532. // Lens flares
  21533. this.lensFlaresEnabled = true;
  21534. this.lensFlareSystems = new Array();
  21535. // Collisions
  21536. this.collisionsEnabled = true;
  21537. /** Defines the gravity applied to this scene */
  21538. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21539. // Postprocesses
  21540. this.postProcesses = new Array();
  21541. this.postProcessesEnabled = true;
  21542. // Customs render targets
  21543. this.renderTargetsEnabled = true;
  21544. this.dumpNextRenderTargets = false;
  21545. this.customRenderTargets = new Array();
  21546. // Imported meshes
  21547. this.importedMeshesFiles = new Array();
  21548. // Probes
  21549. this.probesEnabled = true;
  21550. this.reflectionProbes = new Array();
  21551. this._actionManagers = new Array();
  21552. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21553. // Procedural textures
  21554. this.proceduralTexturesEnabled = true;
  21555. this._proceduralTextures = new Array();
  21556. this.soundTracks = new Array();
  21557. this._audioEnabled = true;
  21558. this._headphone = false;
  21559. // Performance counters
  21560. this._totalVertices = new BABYLON.PerfCounter();
  21561. this._activeIndices = new BABYLON.PerfCounter();
  21562. this._activeParticles = new BABYLON.PerfCounter();
  21563. this._activeBones = new BABYLON.PerfCounter();
  21564. this._animationTime = 0;
  21565. this.animationTimeScale = 1;
  21566. this._renderId = 0;
  21567. this._executeWhenReadyTimeoutId = -1;
  21568. this._intermediateRendering = false;
  21569. this._viewUpdateFlag = -1;
  21570. this._projectionUpdateFlag = -1;
  21571. this._alternateViewUpdateFlag = -1;
  21572. this._alternateProjectionUpdateFlag = -1;
  21573. this._toBeDisposed = new BABYLON.SmartArray(256);
  21574. this._activeRequests = new Array();
  21575. this._pendingData = new Array();
  21576. this._isDisposed = false;
  21577. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21578. this._activeMeshes = new BABYLON.SmartArray(256);
  21579. this._processedMaterials = new BABYLON.SmartArray(256);
  21580. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21581. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21582. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21583. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21584. this._activeAnimatables = new Array();
  21585. this._transformMatrix = BABYLON.Matrix.Zero();
  21586. this._useAlternateCameraConfiguration = false;
  21587. this._alternateRendering = false;
  21588. this.requireLightSorting = false;
  21589. this._depthRenderer = {};
  21590. this._activeMeshesFrozen = false;
  21591. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21592. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21593. this._engine.scenes.push(this);
  21594. this._uid = null;
  21595. this._renderingManager = new BABYLON.RenderingManager(this);
  21596. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21597. if (BABYLON.OutlineRenderer) {
  21598. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21599. }
  21600. if (BABYLON.Tools.IsWindowObjectExist()) {
  21601. this.attachControl();
  21602. }
  21603. //simplification queue
  21604. if (BABYLON.SimplificationQueue) {
  21605. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21606. }
  21607. //collision coordinator initialization. For now legacy per default.
  21608. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21609. // Uniform Buffer
  21610. this._createUbo();
  21611. // Default Image processing definition.
  21612. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21613. }
  21614. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21615. /** The fog is deactivated */
  21616. get: function () {
  21617. return Scene._FOGMODE_NONE;
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21623. /** The fog density is following an exponential function */
  21624. get: function () {
  21625. return Scene._FOGMODE_EXP;
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21631. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21632. get: function () {
  21633. return Scene._FOGMODE_EXP2;
  21634. },
  21635. enumerable: true,
  21636. configurable: true
  21637. });
  21638. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21639. /** The fog density is following a linear function. */
  21640. get: function () {
  21641. return Scene._FOGMODE_LINEAR;
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21647. /**
  21648. * Texture used in all pbr material as the reflection texture.
  21649. * As in the majority of the scene they are the same (exception for multi room and so on),
  21650. * this is easier to reference from here than from all the materials.
  21651. */
  21652. get: function () {
  21653. return this._environmentTexture;
  21654. },
  21655. /**
  21656. * Texture used in all pbr material as the reflection texture.
  21657. * As in the majority of the scene they are the same (exception for multi room and so on),
  21658. * this is easier to set here than in all the materials.
  21659. */
  21660. set: function (value) {
  21661. if (this._environmentTexture === value) {
  21662. return;
  21663. }
  21664. this._environmentTexture = value;
  21665. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21666. },
  21667. enumerable: true,
  21668. configurable: true
  21669. });
  21670. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21671. /**
  21672. * Default image processing configuration used either in the rendering
  21673. * Forward main pass or through the imageProcessingPostProcess if present.
  21674. * As in the majority of the scene they are the same (exception for multi camera),
  21675. * this is easier to reference from here than from all the materials and post process.
  21676. *
  21677. * No setter as we it is a shared configuration, you can set the values instead.
  21678. */
  21679. get: function () {
  21680. return this._imageProcessingConfiguration;
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21686. get: function () {
  21687. return this._forcePointsCloud;
  21688. },
  21689. set: function (value) {
  21690. if (this._forcePointsCloud === value) {
  21691. return;
  21692. }
  21693. this._forcePointsCloud = value;
  21694. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(Scene.prototype, "onDispose", {
  21700. /** A function to be executed when this scene is disposed. */
  21701. set: function (callback) {
  21702. if (this._onDisposeObserver) {
  21703. this.onDisposeObservable.remove(this._onDisposeObserver);
  21704. }
  21705. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21706. },
  21707. enumerable: true,
  21708. configurable: true
  21709. });
  21710. Object.defineProperty(Scene.prototype, "beforeRender", {
  21711. /** A function to be executed before rendering this scene */
  21712. set: function (callback) {
  21713. if (this._onBeforeRenderObserver) {
  21714. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21715. }
  21716. if (callback) {
  21717. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21718. }
  21719. },
  21720. enumerable: true,
  21721. configurable: true
  21722. });
  21723. Object.defineProperty(Scene.prototype, "afterRender", {
  21724. /** A function to be executed after rendering this scene */
  21725. set: function (callback) {
  21726. if (this._onAfterRenderObserver) {
  21727. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21728. }
  21729. if (callback) {
  21730. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21731. }
  21732. },
  21733. enumerable: true,
  21734. configurable: true
  21735. });
  21736. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21737. set: function (callback) {
  21738. if (this._onBeforeCameraRenderObserver) {
  21739. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21740. }
  21741. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21742. },
  21743. enumerable: true,
  21744. configurable: true
  21745. });
  21746. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21747. set: function (callback) {
  21748. if (this._onAfterCameraRenderObserver) {
  21749. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21750. }
  21751. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21752. },
  21753. enumerable: true,
  21754. configurable: true
  21755. });
  21756. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21757. get: function () {
  21758. if (!this._gamepadManager) {
  21759. this._gamepadManager = new BABYLON.GamepadManager(this);
  21760. }
  21761. return this._gamepadManager;
  21762. },
  21763. enumerable: true,
  21764. configurable: true
  21765. });
  21766. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21767. get: function () {
  21768. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21769. },
  21770. enumerable: true,
  21771. configurable: true
  21772. });
  21773. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21774. get: function () {
  21775. return this._useRightHandedSystem;
  21776. },
  21777. set: function (value) {
  21778. if (this._useRightHandedSystem === value) {
  21779. return;
  21780. }
  21781. this._useRightHandedSystem = value;
  21782. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21783. },
  21784. enumerable: true,
  21785. configurable: true
  21786. });
  21787. Scene.prototype.setStepId = function (newStepId) {
  21788. this._currentStepId = newStepId;
  21789. };
  21790. ;
  21791. Scene.prototype.getStepId = function () {
  21792. return this._currentStepId;
  21793. };
  21794. ;
  21795. Scene.prototype.getInternalStep = function () {
  21796. return this._currentInternalStep;
  21797. };
  21798. ;
  21799. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21800. get: function () {
  21801. return this._fogEnabled;
  21802. },
  21803. /**
  21804. * is fog enabled on this scene.
  21805. */
  21806. set: function (value) {
  21807. if (this._fogEnabled === value) {
  21808. return;
  21809. }
  21810. this._fogEnabled = value;
  21811. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. Object.defineProperty(Scene.prototype, "fogMode", {
  21817. get: function () {
  21818. return this._fogMode;
  21819. },
  21820. set: function (value) {
  21821. if (this._fogMode === value) {
  21822. return;
  21823. }
  21824. this._fogMode = value;
  21825. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21831. get: function () {
  21832. return this._shadowsEnabled;
  21833. },
  21834. set: function (value) {
  21835. if (this._shadowsEnabled === value) {
  21836. return;
  21837. }
  21838. this._shadowsEnabled = value;
  21839. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21840. },
  21841. enumerable: true,
  21842. configurable: true
  21843. });
  21844. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21845. get: function () {
  21846. return this._lightsEnabled;
  21847. },
  21848. set: function (value) {
  21849. if (this._lightsEnabled === value) {
  21850. return;
  21851. }
  21852. this._lightsEnabled = value;
  21853. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21859. /** The default material used on meshes when no material is affected */
  21860. get: function () {
  21861. if (!this._defaultMaterial) {
  21862. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21863. }
  21864. return this._defaultMaterial;
  21865. },
  21866. /** The default material used on meshes when no material is affected */
  21867. set: function (value) {
  21868. this._defaultMaterial = value;
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21874. get: function () {
  21875. return this._texturesEnabled;
  21876. },
  21877. set: function (value) {
  21878. if (this._texturesEnabled === value) {
  21879. return;
  21880. }
  21881. this._texturesEnabled = value;
  21882. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21883. },
  21884. enumerable: true,
  21885. configurable: true
  21886. });
  21887. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21888. get: function () {
  21889. return this._skeletonsEnabled;
  21890. },
  21891. set: function (value) {
  21892. if (this._skeletonsEnabled === value) {
  21893. return;
  21894. }
  21895. this._skeletonsEnabled = value;
  21896. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21902. get: function () {
  21903. if (!this._postProcessRenderPipelineManager) {
  21904. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21905. }
  21906. return this._postProcessRenderPipelineManager;
  21907. },
  21908. enumerable: true,
  21909. configurable: true
  21910. });
  21911. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21912. get: function () {
  21913. if (!this._mainSoundTrack) {
  21914. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21915. }
  21916. return this._mainSoundTrack;
  21917. },
  21918. enumerable: true,
  21919. configurable: true
  21920. });
  21921. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21922. get: function () {
  21923. return this._alternateRendering;
  21924. },
  21925. enumerable: true,
  21926. configurable: true
  21927. });
  21928. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21929. get: function () {
  21930. return this._frustumPlanes;
  21931. },
  21932. enumerable: true,
  21933. configurable: true
  21934. });
  21935. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21936. /**
  21937. * Gets the current geometry buffer associated to the scene.
  21938. */
  21939. get: function () {
  21940. return this._geometryBufferRenderer;
  21941. },
  21942. /**
  21943. * Sets the current geometry buffer for the scene.
  21944. */
  21945. set: function (geometryBufferRenderer) {
  21946. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21947. this._geometryBufferRenderer = geometryBufferRenderer;
  21948. }
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Scene.prototype, "debugLayer", {
  21954. // Properties
  21955. get: function () {
  21956. if (!this._debugLayer) {
  21957. this._debugLayer = new BABYLON.DebugLayer(this);
  21958. }
  21959. return this._debugLayer;
  21960. },
  21961. enumerable: true,
  21962. configurable: true
  21963. });
  21964. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21965. get: function () {
  21966. return this._workerCollisions;
  21967. },
  21968. set: function (enabled) {
  21969. if (!BABYLON.CollisionCoordinatorLegacy) {
  21970. return;
  21971. }
  21972. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  21973. this._workerCollisions = enabled;
  21974. if (this.collisionCoordinator) {
  21975. this.collisionCoordinator.destroy();
  21976. }
  21977. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21978. this.collisionCoordinator.init(this);
  21979. },
  21980. enumerable: true,
  21981. configurable: true
  21982. });
  21983. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21984. get: function () {
  21985. return this._selectionOctree;
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21991. /**
  21992. * The mesh that is currently under the pointer.
  21993. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21994. */
  21995. get: function () {
  21996. return this._pointerOverMesh;
  21997. },
  21998. enumerable: true,
  21999. configurable: true
  22000. });
  22001. Object.defineProperty(Scene.prototype, "pointerX", {
  22002. /**
  22003. * Current on-screen X position of the pointer
  22004. * @return {number} X position of the pointer
  22005. */
  22006. get: function () {
  22007. return this._pointerX;
  22008. },
  22009. enumerable: true,
  22010. configurable: true
  22011. });
  22012. Object.defineProperty(Scene.prototype, "pointerY", {
  22013. /**
  22014. * Current on-screen Y position of the pointer
  22015. * @return {number} Y position of the pointer
  22016. */
  22017. get: function () {
  22018. return this._pointerY;
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Scene.prototype.getCachedMaterial = function () {
  22024. return this._cachedMaterial;
  22025. };
  22026. Scene.prototype.getCachedEffect = function () {
  22027. return this._cachedEffect;
  22028. };
  22029. Scene.prototype.getCachedVisibility = function () {
  22030. return this._cachedVisibility;
  22031. };
  22032. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22033. if (visibility === void 0) { visibility = 1; }
  22034. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22035. };
  22036. Scene.prototype.getBoundingBoxRenderer = function () {
  22037. if (!this._boundingBoxRenderer) {
  22038. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22039. }
  22040. return this._boundingBoxRenderer;
  22041. };
  22042. Scene.prototype.getOutlineRenderer = function () {
  22043. return this._outlineRenderer;
  22044. };
  22045. Scene.prototype.getEngine = function () {
  22046. return this._engine;
  22047. };
  22048. Scene.prototype.getTotalVertices = function () {
  22049. return this._totalVertices.current;
  22050. };
  22051. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22052. get: function () {
  22053. return this._totalVertices;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Scene.prototype.getActiveIndices = function () {
  22059. return this._activeIndices.current;
  22060. };
  22061. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22062. get: function () {
  22063. return this._activeIndices;
  22064. },
  22065. enumerable: true,
  22066. configurable: true
  22067. });
  22068. Scene.prototype.getActiveParticles = function () {
  22069. return this._activeParticles.current;
  22070. };
  22071. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22072. get: function () {
  22073. return this._activeParticles;
  22074. },
  22075. enumerable: true,
  22076. configurable: true
  22077. });
  22078. Scene.prototype.getActiveBones = function () {
  22079. return this._activeBones.current;
  22080. };
  22081. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22082. get: function () {
  22083. return this._activeBones;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. // Stats
  22089. Scene.prototype.getInterFramePerfCounter = function () {
  22090. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22091. return 0;
  22092. };
  22093. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22094. get: function () {
  22095. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22096. return null;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. Scene.prototype.getLastFrameDuration = function () {
  22102. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22103. return 0;
  22104. };
  22105. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22106. get: function () {
  22107. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22108. return null;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22114. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22115. return 0;
  22116. };
  22117. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22118. get: function () {
  22119. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22120. return null;
  22121. },
  22122. enumerable: true,
  22123. configurable: true
  22124. });
  22125. Scene.prototype.getActiveMeshes = function () {
  22126. return this._activeMeshes;
  22127. };
  22128. Scene.prototype.getRenderTargetsDuration = function () {
  22129. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22130. return 0;
  22131. };
  22132. Scene.prototype.getRenderDuration = function () {
  22133. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22134. return 0;
  22135. };
  22136. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22137. get: function () {
  22138. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22139. return null;
  22140. },
  22141. enumerable: true,
  22142. configurable: true
  22143. });
  22144. Scene.prototype.getParticlesDuration = function () {
  22145. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22146. return 0;
  22147. };
  22148. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22149. get: function () {
  22150. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22151. return null;
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. Scene.prototype.getSpritesDuration = function () {
  22157. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22158. return 0;
  22159. };
  22160. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22161. get: function () {
  22162. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22163. return null;
  22164. },
  22165. enumerable: true,
  22166. configurable: true
  22167. });
  22168. Scene.prototype.getAnimationRatio = function () {
  22169. return this._animationRatio;
  22170. };
  22171. Scene.prototype.getRenderId = function () {
  22172. return this._renderId;
  22173. };
  22174. Scene.prototype.incrementRenderId = function () {
  22175. this._renderId++;
  22176. };
  22177. Scene.prototype._updatePointerPosition = function (evt) {
  22178. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22179. if (!canvasRect) {
  22180. return;
  22181. }
  22182. this._pointerX = evt.clientX - canvasRect.left;
  22183. this._pointerY = evt.clientY - canvasRect.top;
  22184. this._unTranslatedPointerX = this._pointerX;
  22185. this._unTranslatedPointerY = this._pointerY;
  22186. };
  22187. Scene.prototype._createUbo = function () {
  22188. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22189. this._sceneUbo.addUniform("viewProjection", 16);
  22190. this._sceneUbo.addUniform("view", 16);
  22191. };
  22192. Scene.prototype._createAlternateUbo = function () {
  22193. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22194. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22195. this._alternateSceneUbo.addUniform("view", 16);
  22196. };
  22197. // Pointers handling
  22198. /**
  22199. * Use this method to simulate a pointer move on a mesh
  22200. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22201. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22202. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22203. */
  22204. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22205. var evt = new PointerEvent("pointermove", pointerEventInit);
  22206. return this._processPointerMove(pickResult, evt);
  22207. };
  22208. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22209. var canvas = this._engine.getRenderingCanvas();
  22210. if (!canvas) {
  22211. return this;
  22212. }
  22213. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22214. this.setPointerOverSprite(null);
  22215. this.setPointerOverMesh(pickResult.pickedMesh);
  22216. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22217. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22218. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22219. }
  22220. else {
  22221. canvas.style.cursor = this.hoverCursor;
  22222. }
  22223. }
  22224. else {
  22225. canvas.style.cursor = this.defaultCursor;
  22226. }
  22227. }
  22228. else {
  22229. this.setPointerOverMesh(null);
  22230. // Sprites
  22231. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22232. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22233. this.setPointerOverSprite(pickResult.pickedSprite);
  22234. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22235. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22236. }
  22237. else {
  22238. canvas.style.cursor = this.hoverCursor;
  22239. }
  22240. }
  22241. else {
  22242. this.setPointerOverSprite(null);
  22243. // Restore pointer
  22244. canvas.style.cursor = this.defaultCursor;
  22245. }
  22246. }
  22247. if (pickResult) {
  22248. if (this.onPointerMove) {
  22249. this.onPointerMove(evt, pickResult);
  22250. }
  22251. if (this.onPointerObservable.hasObservers()) {
  22252. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22253. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22254. this.onPointerObservable.notifyObservers(pi, type);
  22255. }
  22256. }
  22257. return this;
  22258. };
  22259. /**
  22260. * Use this method to simulate a pointer down on a mesh
  22261. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22262. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22263. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22264. */
  22265. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22266. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22267. return this._processPointerDown(pickResult, evt);
  22268. };
  22269. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22270. var _this = this;
  22271. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22272. this._pickedDownMesh = pickResult.pickedMesh;
  22273. var actionManager = pickResult.pickedMesh.actionManager;
  22274. if (actionManager) {
  22275. if (actionManager.hasPickTriggers) {
  22276. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22277. switch (evt.button) {
  22278. case 0:
  22279. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22280. break;
  22281. case 1:
  22282. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22283. break;
  22284. case 2:
  22285. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22286. break;
  22287. }
  22288. }
  22289. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22290. window.setTimeout(function () {
  22291. 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);
  22292. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22293. if (_this._totalPointersPressed !== 0 &&
  22294. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22295. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22296. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22297. _this._startingPointerTime = 0;
  22298. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22299. }
  22300. }
  22301. }, Scene.LongPressDelay);
  22302. }
  22303. }
  22304. }
  22305. if (pickResult) {
  22306. if (this.onPointerDown) {
  22307. this.onPointerDown(evt, pickResult);
  22308. }
  22309. if (this.onPointerObservable.hasObservers()) {
  22310. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22311. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22312. this.onPointerObservable.notifyObservers(pi, type);
  22313. }
  22314. }
  22315. return this;
  22316. };
  22317. /**
  22318. * Use this method to simulate a pointer up on a mesh
  22319. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22320. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22321. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22322. */
  22323. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22324. var evt = new PointerEvent("pointerup", pointerEventInit);
  22325. var clickInfo = new ClickInfo();
  22326. clickInfo.singleClick = true;
  22327. clickInfo.ignore = true;
  22328. return this._processPointerUp(pickResult, evt, clickInfo);
  22329. };
  22330. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22331. if (pickResult && pickResult && pickResult.pickedMesh) {
  22332. this._pickedUpMesh = pickResult.pickedMesh;
  22333. if (this._pickedDownMesh === this._pickedUpMesh) {
  22334. if (this.onPointerPick) {
  22335. this.onPointerPick(evt, pickResult);
  22336. }
  22337. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22338. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22339. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22340. this.onPointerObservable.notifyObservers(pi, type);
  22341. }
  22342. }
  22343. if (pickResult.pickedMesh.actionManager) {
  22344. if (clickInfo.ignore) {
  22345. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22346. }
  22347. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22348. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22349. }
  22350. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22351. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22352. }
  22353. }
  22354. }
  22355. if (this._pickedDownMesh &&
  22356. this._pickedDownMesh.actionManager &&
  22357. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22358. this._pickedDownMesh !== this._pickedUpMesh) {
  22359. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22360. }
  22361. if (this.onPointerUp) {
  22362. this.onPointerUp(evt, pickResult);
  22363. }
  22364. if (this.onPointerObservable.hasObservers()) {
  22365. if (!clickInfo.ignore) {
  22366. if (!clickInfo.hasSwiped) {
  22367. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22368. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22369. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22370. this.onPointerObservable.notifyObservers(pi, type);
  22371. }
  22372. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22373. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22374. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22375. this.onPointerObservable.notifyObservers(pi, type);
  22376. }
  22377. }
  22378. }
  22379. else {
  22380. var type = BABYLON.PointerEventTypes.POINTERUP;
  22381. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22382. this.onPointerObservable.notifyObservers(pi, type);
  22383. }
  22384. }
  22385. return this;
  22386. };
  22387. /**
  22388. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22389. * @param attachUp defines if you want to attach events to pointerup
  22390. * @param attachDown defines if you want to attach events to pointerdown
  22391. * @param attachMove defines if you want to attach events to pointermove
  22392. */
  22393. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22394. var _this = this;
  22395. if (attachUp === void 0) { attachUp = true; }
  22396. if (attachDown === void 0) { attachDown = true; }
  22397. if (attachMove === void 0) { attachMove = true; }
  22398. this._initActionManager = function (act, clickInfo) {
  22399. if (!_this._meshPickProceed) {
  22400. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22401. _this._currentPickResult = pickResult;
  22402. if (pickResult) {
  22403. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22404. }
  22405. _this._meshPickProceed = true;
  22406. }
  22407. return act;
  22408. };
  22409. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22410. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22411. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22412. btn !== _this._previousButtonPressed) {
  22413. _this._doubleClickOccured = false;
  22414. clickInfo.singleClick = true;
  22415. clickInfo.ignore = false;
  22416. cb(clickInfo, _this._currentPickResult);
  22417. }
  22418. };
  22419. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22420. var clickInfo = new ClickInfo();
  22421. _this._currentPickResult = null;
  22422. var act = null;
  22423. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22424. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22425. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22426. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22427. act = _this._initActionManager(act, clickInfo);
  22428. if (act)
  22429. checkPicking = act.hasPickTriggers;
  22430. }
  22431. if (checkPicking) {
  22432. var btn = evt.button;
  22433. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22434. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22435. if (!clickInfo.hasSwiped) {
  22436. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22437. if (!checkSingleClickImmediately) {
  22438. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22439. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22440. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22441. act = _this._initActionManager(act, clickInfo);
  22442. if (act)
  22443. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22444. }
  22445. }
  22446. if (checkSingleClickImmediately) {
  22447. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22448. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22449. btn !== _this._previousButtonPressed) {
  22450. clickInfo.singleClick = true;
  22451. cb(clickInfo, _this._currentPickResult);
  22452. }
  22453. }
  22454. else {
  22455. // wait that no double click has been raised during the double click delay
  22456. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22457. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22458. }
  22459. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22460. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22461. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22462. act = _this._initActionManager(act, clickInfo);
  22463. if (act)
  22464. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22465. }
  22466. if (checkDoubleClick) {
  22467. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22468. if (btn === _this._previousButtonPressed &&
  22469. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22470. !_this._doubleClickOccured) {
  22471. // pointer has not moved for 2 clicks, it's a double click
  22472. if (!clickInfo.hasSwiped &&
  22473. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22474. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22475. _this._previousStartingPointerTime = 0;
  22476. _this._doubleClickOccured = true;
  22477. clickInfo.doubleClick = true;
  22478. clickInfo.ignore = false;
  22479. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22480. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22481. }
  22482. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22483. cb(clickInfo, _this._currentPickResult);
  22484. }
  22485. else {
  22486. _this._doubleClickOccured = false;
  22487. _this._previousStartingPointerTime = _this._startingPointerTime;
  22488. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22489. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22490. _this._previousButtonPressed = btn;
  22491. if (Scene.ExclusiveDoubleClickMode) {
  22492. if (_this._previousDelayedSimpleClickTimeout) {
  22493. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22494. }
  22495. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22496. cb(clickInfo, _this._previousPickResult);
  22497. }
  22498. else {
  22499. cb(clickInfo, _this._currentPickResult);
  22500. }
  22501. }
  22502. }
  22503. else {
  22504. _this._doubleClickOccured = false;
  22505. _this._previousStartingPointerTime = _this._startingPointerTime;
  22506. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22507. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22508. _this._previousButtonPressed = btn;
  22509. }
  22510. }
  22511. }
  22512. }
  22513. clickInfo.ignore = true;
  22514. cb(clickInfo, _this._currentPickResult);
  22515. };
  22516. this._spritePredicate = function (sprite) {
  22517. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22518. };
  22519. this._onPointerMove = function (evt) {
  22520. _this._updatePointerPosition(evt);
  22521. // PreObservable support
  22522. if (_this.onPrePointerObservable.hasObservers()) {
  22523. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22524. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22525. _this.onPrePointerObservable.notifyObservers(pi, type);
  22526. if (pi.skipOnPointerObservable) {
  22527. return;
  22528. }
  22529. }
  22530. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22531. return;
  22532. }
  22533. if (!_this.pointerMovePredicate) {
  22534. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22535. }
  22536. // Meshes
  22537. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22538. _this._processPointerMove(pickResult, evt);
  22539. };
  22540. this._onPointerDown = function (evt) {
  22541. _this._totalPointersPressed++;
  22542. _this._pickedDownMesh = null;
  22543. _this._meshPickProceed = false;
  22544. _this._updatePointerPosition(evt);
  22545. if (_this.preventDefaultOnPointerDown && canvas) {
  22546. evt.preventDefault();
  22547. canvas.focus();
  22548. }
  22549. // PreObservable support
  22550. if (_this.onPrePointerObservable.hasObservers()) {
  22551. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22552. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22553. _this.onPrePointerObservable.notifyObservers(pi, type);
  22554. if (pi.skipOnPointerObservable) {
  22555. return;
  22556. }
  22557. }
  22558. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22559. return;
  22560. }
  22561. _this._startingPointerPosition.x = _this._pointerX;
  22562. _this._startingPointerPosition.y = _this._pointerY;
  22563. _this._startingPointerTime = new Date().getTime();
  22564. if (!_this.pointerDownPredicate) {
  22565. _this.pointerDownPredicate = function (mesh) {
  22566. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22567. };
  22568. }
  22569. // Meshes
  22570. _this._pickedDownMesh = null;
  22571. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22572. _this._processPointerDown(pickResult, evt);
  22573. // Sprites
  22574. _this._pickedDownSprite = null;
  22575. if (_this.spriteManagers.length > 0) {
  22576. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22577. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22578. if (pickResult.pickedSprite.actionManager) {
  22579. _this._pickedDownSprite = pickResult.pickedSprite;
  22580. switch (evt.button) {
  22581. case 0:
  22582. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22583. break;
  22584. case 1:
  22585. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22586. break;
  22587. case 2:
  22588. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22589. break;
  22590. }
  22591. if (pickResult.pickedSprite.actionManager) {
  22592. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22593. }
  22594. }
  22595. }
  22596. }
  22597. };
  22598. this._onPointerUp = function (evt) {
  22599. if (_this._totalPointersPressed === 0) {
  22600. return; // So we need to test it the pointer down was pressed before.
  22601. }
  22602. _this._totalPointersPressed--;
  22603. _this._pickedUpMesh = null;
  22604. _this._meshPickProceed = false;
  22605. _this._updatePointerPosition(evt);
  22606. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22607. // PreObservable support
  22608. if (_this.onPrePointerObservable.hasObservers()) {
  22609. if (!clickInfo.ignore) {
  22610. if (!clickInfo.hasSwiped) {
  22611. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22612. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22613. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22614. _this.onPrePointerObservable.notifyObservers(pi, type);
  22615. if (pi.skipOnPointerObservable) {
  22616. return;
  22617. }
  22618. }
  22619. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22620. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22621. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22622. _this.onPrePointerObservable.notifyObservers(pi, type);
  22623. if (pi.skipOnPointerObservable) {
  22624. return;
  22625. }
  22626. }
  22627. }
  22628. }
  22629. else {
  22630. var type = BABYLON.PointerEventTypes.POINTERUP;
  22631. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22632. _this.onPrePointerObservable.notifyObservers(pi, type);
  22633. if (pi.skipOnPointerObservable) {
  22634. return;
  22635. }
  22636. }
  22637. }
  22638. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22639. return;
  22640. }
  22641. if (!_this.pointerUpPredicate) {
  22642. _this.pointerUpPredicate = function (mesh) {
  22643. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22644. };
  22645. }
  22646. // Meshes
  22647. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22648. _this._initActionManager(null, clickInfo);
  22649. }
  22650. if (!pickResult) {
  22651. pickResult = _this._currentPickResult;
  22652. }
  22653. _this._processPointerUp(pickResult, evt, clickInfo);
  22654. // Sprites
  22655. if (_this.spriteManagers.length > 0) {
  22656. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22657. if (spritePickResult) {
  22658. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22659. if (spritePickResult.pickedSprite.actionManager) {
  22660. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22661. if (spritePickResult.pickedSprite.actionManager) {
  22662. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22663. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22664. }
  22665. }
  22666. }
  22667. }
  22668. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22669. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22670. }
  22671. }
  22672. }
  22673. _this._previousPickResult = _this._currentPickResult;
  22674. });
  22675. };
  22676. this._onKeyDown = function (evt) {
  22677. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22678. if (_this.onPreKeyboardObservable.hasObservers()) {
  22679. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22680. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22681. if (pi.skipOnPointerObservable) {
  22682. return;
  22683. }
  22684. }
  22685. if (_this.onKeyboardObservable.hasObservers()) {
  22686. var pi = new BABYLON.KeyboardInfo(type, evt);
  22687. _this.onKeyboardObservable.notifyObservers(pi, type);
  22688. }
  22689. if (_this.actionManager) {
  22690. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22691. }
  22692. };
  22693. this._onKeyUp = function (evt) {
  22694. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22695. if (_this.onPreKeyboardObservable.hasObservers()) {
  22696. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22697. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22698. if (pi.skipOnPointerObservable) {
  22699. return;
  22700. }
  22701. }
  22702. if (_this.onKeyboardObservable.hasObservers()) {
  22703. var pi = new BABYLON.KeyboardInfo(type, evt);
  22704. _this.onKeyboardObservable.notifyObservers(pi, type);
  22705. }
  22706. if (_this.actionManager) {
  22707. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22708. }
  22709. };
  22710. var engine = this.getEngine();
  22711. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22712. if (!canvas) {
  22713. return;
  22714. }
  22715. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22716. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22717. });
  22718. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22719. if (!canvas) {
  22720. return;
  22721. }
  22722. canvas.removeEventListener("keydown", _this._onKeyDown);
  22723. canvas.removeEventListener("keyup", _this._onKeyUp);
  22724. });
  22725. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22726. var canvas = this._engine.getRenderingCanvas();
  22727. if (!canvas) {
  22728. return;
  22729. }
  22730. if (attachMove) {
  22731. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22732. // Wheel
  22733. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22734. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22735. }
  22736. if (attachDown) {
  22737. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22738. }
  22739. if (attachUp) {
  22740. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22741. }
  22742. canvas.tabIndex = 1;
  22743. };
  22744. Scene.prototype.detachControl = function () {
  22745. var engine = this.getEngine();
  22746. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22747. var canvas = engine.getRenderingCanvas();
  22748. if (!canvas) {
  22749. return;
  22750. }
  22751. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22752. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22753. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22754. if (this._onCanvasBlurObserver) {
  22755. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22756. }
  22757. if (this._onCanvasFocusObserver) {
  22758. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22759. }
  22760. // Wheel
  22761. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22762. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22763. // Keyboard
  22764. canvas.removeEventListener("keydown", this._onKeyDown);
  22765. canvas.removeEventListener("keyup", this._onKeyUp);
  22766. // Observables
  22767. this.onKeyboardObservable.clear();
  22768. this.onPreKeyboardObservable.clear();
  22769. this.onPointerObservable.clear();
  22770. this.onPrePointerObservable.clear();
  22771. };
  22772. /**
  22773. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22774. * Delay loaded resources are not taking in account
  22775. * @return true if all required resources are ready
  22776. */
  22777. Scene.prototype.isReady = function () {
  22778. if (this._isDisposed) {
  22779. return false;
  22780. }
  22781. if (this._pendingData.length > 0) {
  22782. return false;
  22783. }
  22784. var index;
  22785. var engine = this.getEngine();
  22786. // Geometries
  22787. for (index = 0; index < this._geometries.length; index++) {
  22788. var geometry = this._geometries[index];
  22789. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22790. return false;
  22791. }
  22792. }
  22793. // Meshes
  22794. for (index = 0; index < this.meshes.length; index++) {
  22795. var mesh = this.meshes[index];
  22796. if (!mesh.isEnabled()) {
  22797. continue;
  22798. }
  22799. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22800. continue;
  22801. }
  22802. if (!mesh.isReady(true)) {
  22803. return false;
  22804. }
  22805. // Effect layers
  22806. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22807. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22808. var layer = _a[_i];
  22809. if (!layer.hasMesh(mesh)) {
  22810. continue;
  22811. }
  22812. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22813. var subMesh = _c[_b];
  22814. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22815. return false;
  22816. }
  22817. }
  22818. }
  22819. }
  22820. return true;
  22821. };
  22822. Scene.prototype.resetCachedMaterial = function () {
  22823. this._cachedMaterial = null;
  22824. this._cachedEffect = null;
  22825. this._cachedVisibility = null;
  22826. };
  22827. Scene.prototype.registerBeforeRender = function (func) {
  22828. this.onBeforeRenderObservable.add(func);
  22829. };
  22830. Scene.prototype.unregisterBeforeRender = function (func) {
  22831. this.onBeforeRenderObservable.removeCallback(func);
  22832. };
  22833. Scene.prototype.registerAfterRender = function (func) {
  22834. this.onAfterRenderObservable.add(func);
  22835. };
  22836. Scene.prototype.unregisterAfterRender = function (func) {
  22837. this.onAfterRenderObservable.removeCallback(func);
  22838. };
  22839. Scene.prototype._executeOnceBeforeRender = function (func) {
  22840. var _this = this;
  22841. var execFunc = function () {
  22842. func();
  22843. setTimeout(function () {
  22844. _this.unregisterBeforeRender(execFunc);
  22845. });
  22846. };
  22847. this.registerBeforeRender(execFunc);
  22848. };
  22849. /**
  22850. * The provided function will run before render once and will be disposed afterwards.
  22851. * A timeout delay can be provided so that the function will be executed in N ms.
  22852. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22853. * @param func The function to be executed.
  22854. * @param timeout optional delay in ms
  22855. */
  22856. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22857. var _this = this;
  22858. if (timeout !== undefined) {
  22859. setTimeout(function () {
  22860. _this._executeOnceBeforeRender(func);
  22861. }, timeout);
  22862. }
  22863. else {
  22864. this._executeOnceBeforeRender(func);
  22865. }
  22866. };
  22867. Scene.prototype._addPendingData = function (data) {
  22868. this._pendingData.push(data);
  22869. };
  22870. Scene.prototype._removePendingData = function (data) {
  22871. var wasLoading = this.isLoading;
  22872. var index = this._pendingData.indexOf(data);
  22873. if (index !== -1) {
  22874. this._pendingData.splice(index, 1);
  22875. }
  22876. if (wasLoading && !this.isLoading) {
  22877. this.onDataLoadedObservable.notifyObservers(this);
  22878. }
  22879. };
  22880. Scene.prototype.getWaitingItemsCount = function () {
  22881. return this._pendingData.length;
  22882. };
  22883. Object.defineProperty(Scene.prototype, "isLoading", {
  22884. get: function () {
  22885. return this._pendingData.length > 0;
  22886. },
  22887. enumerable: true,
  22888. configurable: true
  22889. });
  22890. /**
  22891. * Registers a function to be executed when the scene is ready.
  22892. * @param {Function} func - the function to be executed.
  22893. */
  22894. Scene.prototype.executeWhenReady = function (func) {
  22895. var _this = this;
  22896. this.onReadyObservable.add(func);
  22897. if (this._executeWhenReadyTimeoutId !== -1) {
  22898. return;
  22899. }
  22900. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22901. _this._checkIsReady();
  22902. }, 150);
  22903. };
  22904. /**
  22905. * Returns a promise that resolves when the scene is ready.
  22906. * @returns A promise that resolves when the scene is ready.
  22907. */
  22908. Scene.prototype.whenReadyAsync = function () {
  22909. var _this = this;
  22910. return new Promise(function (resolve) {
  22911. _this.executeWhenReady(function () {
  22912. resolve();
  22913. });
  22914. });
  22915. };
  22916. Scene.prototype._checkIsReady = function () {
  22917. var _this = this;
  22918. if (this.isReady()) {
  22919. this.onReadyObservable.notifyObservers(this);
  22920. this.onReadyObservable.clear();
  22921. this._executeWhenReadyTimeoutId = -1;
  22922. return;
  22923. }
  22924. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22925. _this._checkIsReady();
  22926. }, 150);
  22927. };
  22928. // Animations
  22929. /**
  22930. * Will start the animation sequence of a given target
  22931. * @param target - the target
  22932. * @param {number} from - from which frame should animation start
  22933. * @param {number} to - till which frame should animation run.
  22934. * @param {boolean} [loop] - should the animation loop
  22935. * @param {number} [speedRatio] - the speed in which to run the animation
  22936. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22937. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22938. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22939. * See BABYLON.Animatable
  22940. */
  22941. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22942. if (speedRatio === void 0) { speedRatio = 1.0; }
  22943. if (from > to && speedRatio > 0) {
  22944. speedRatio *= -1;
  22945. }
  22946. this.stopAnimation(target);
  22947. if (!animatable) {
  22948. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22949. }
  22950. // Local animations
  22951. if (target.animations) {
  22952. animatable.appendAnimations(target, target.animations);
  22953. }
  22954. // Children animations
  22955. if (target.getAnimatables) {
  22956. var animatables = target.getAnimatables();
  22957. for (var index = 0; index < animatables.length; index++) {
  22958. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22959. }
  22960. }
  22961. animatable.reset();
  22962. return animatable;
  22963. };
  22964. /**
  22965. * Begin a new animation on a given node
  22966. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22967. * @param {BABYLON.Animation[]} defines the list of animations to start
  22968. * @param {number} from defines the initial value
  22969. * @param {number} to defines the final value
  22970. * @param {boolean} loop defines if you want animation to loop (off by default)
  22971. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22972. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22973. * @returns the list of created animatables
  22974. */
  22975. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22976. if (speedRatio === undefined) {
  22977. speedRatio = 1.0;
  22978. }
  22979. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22980. return animatable;
  22981. };
  22982. /**
  22983. * Begin a new animation on a given node and its hierarchy
  22984. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22985. * @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.
  22986. * @param {BABYLON.Animation[]} defines the list of animations to start
  22987. * @param {number} from defines the initial value
  22988. * @param {number} to defines the final value
  22989. * @param {boolean} loop defines if you want animation to loop (off by default)
  22990. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22991. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22992. * @returns the list of animatables created for all nodes
  22993. */
  22994. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22995. var children = target.getDescendants(directDescendantsOnly);
  22996. var result = [];
  22997. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22998. var child = children_1[_i];
  22999. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23000. }
  23001. return result;
  23002. };
  23003. Scene.prototype.getAnimatableByTarget = function (target) {
  23004. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23005. if (this._activeAnimatables[index].target === target) {
  23006. return this._activeAnimatables[index];
  23007. }
  23008. }
  23009. return null;
  23010. };
  23011. Object.defineProperty(Scene.prototype, "animatables", {
  23012. get: function () {
  23013. return this._activeAnimatables;
  23014. },
  23015. enumerable: true,
  23016. configurable: true
  23017. });
  23018. /**
  23019. * Will stop the animation of the given target
  23020. * @param target - the target
  23021. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23022. * @see beginAnimation
  23023. */
  23024. Scene.prototype.stopAnimation = function (target, animationName) {
  23025. var animatable = this.getAnimatableByTarget(target);
  23026. if (animatable) {
  23027. animatable.stop(animationName);
  23028. }
  23029. };
  23030. /**
  23031. * Stops and removes all animations that have been applied to the scene
  23032. */
  23033. Scene.prototype.stopAllAnimations = function () {
  23034. if (this._activeAnimatables) {
  23035. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23036. this._activeAnimatables[i].stop();
  23037. }
  23038. this._activeAnimatables = [];
  23039. }
  23040. };
  23041. Scene.prototype._animate = function () {
  23042. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23043. return;
  23044. }
  23045. // Getting time
  23046. var now = BABYLON.Tools.Now;
  23047. if (!this._animationTimeLast) {
  23048. if (this._pendingData.length > 0) {
  23049. return;
  23050. }
  23051. this._animationTimeLast = now;
  23052. }
  23053. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23054. this._animationTime += deltaTime;
  23055. this._animationTimeLast = now;
  23056. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23057. this._activeAnimatables[index]._animate(this._animationTime);
  23058. }
  23059. };
  23060. // Matrix
  23061. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23062. this._useAlternateCameraConfiguration = active;
  23063. };
  23064. Scene.prototype.getViewMatrix = function () {
  23065. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23066. };
  23067. Scene.prototype.getProjectionMatrix = function () {
  23068. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23069. };
  23070. Scene.prototype.getTransformMatrix = function () {
  23071. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23072. };
  23073. Scene.prototype.setTransformMatrix = function (view, projection) {
  23074. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23075. return;
  23076. }
  23077. this._viewUpdateFlag = view.updateFlag;
  23078. this._projectionUpdateFlag = projection.updateFlag;
  23079. this._viewMatrix = view;
  23080. this._projectionMatrix = projection;
  23081. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23082. // Update frustum
  23083. if (!this._frustumPlanes) {
  23084. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23085. }
  23086. else {
  23087. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23088. }
  23089. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23090. var otherCamera = this.activeCamera._alternateCamera;
  23091. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23092. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23093. }
  23094. if (this._sceneUbo.useUbo) {
  23095. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23096. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23097. this._sceneUbo.update();
  23098. }
  23099. };
  23100. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23101. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23102. return;
  23103. }
  23104. this._alternateViewUpdateFlag = view.updateFlag;
  23105. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23106. this._alternateViewMatrix = view;
  23107. this._alternateProjectionMatrix = projection;
  23108. if (!this._alternateTransformMatrix) {
  23109. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23110. }
  23111. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23112. if (!this._alternateSceneUbo) {
  23113. this._createAlternateUbo();
  23114. }
  23115. if (this._alternateSceneUbo.useUbo) {
  23116. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23117. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23118. this._alternateSceneUbo.update();
  23119. }
  23120. };
  23121. Scene.prototype.getSceneUniformBuffer = function () {
  23122. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23123. };
  23124. // Methods
  23125. Scene.prototype.getUniqueId = function () {
  23126. var result = Scene._uniqueIdCounter;
  23127. Scene._uniqueIdCounter++;
  23128. return result;
  23129. };
  23130. Scene.prototype.addMesh = function (newMesh) {
  23131. this.meshes.push(newMesh);
  23132. //notify the collision coordinator
  23133. if (this.collisionCoordinator) {
  23134. this.collisionCoordinator.onMeshAdded(newMesh);
  23135. }
  23136. newMesh._resyncLightSources();
  23137. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23138. };
  23139. Scene.prototype.removeMesh = function (toRemove) {
  23140. var index = this.meshes.indexOf(toRemove);
  23141. if (index !== -1) {
  23142. // Remove from the scene if mesh found
  23143. this.meshes.splice(index, 1);
  23144. }
  23145. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23146. return index;
  23147. };
  23148. Scene.prototype.addTransformNode = function (newTransformNode) {
  23149. this.transformNodes.push(newTransformNode);
  23150. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23151. };
  23152. Scene.prototype.removeTransformNode = function (toRemove) {
  23153. var index = this.transformNodes.indexOf(toRemove);
  23154. if (index !== -1) {
  23155. // Remove from the scene if found
  23156. this.transformNodes.splice(index, 1);
  23157. }
  23158. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23159. return index;
  23160. };
  23161. Scene.prototype.removeSkeleton = function (toRemove) {
  23162. var index = this.skeletons.indexOf(toRemove);
  23163. if (index !== -1) {
  23164. // Remove from the scene if found
  23165. this.skeletons.splice(index, 1);
  23166. }
  23167. return index;
  23168. };
  23169. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23170. var index = this.morphTargetManagers.indexOf(toRemove);
  23171. if (index !== -1) {
  23172. // Remove from the scene if found
  23173. this.morphTargetManagers.splice(index, 1);
  23174. }
  23175. return index;
  23176. };
  23177. Scene.prototype.removeLight = function (toRemove) {
  23178. var index = this.lights.indexOf(toRemove);
  23179. if (index !== -1) {
  23180. // Remove from meshes
  23181. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23182. var mesh = _a[_i];
  23183. mesh._removeLightSource(toRemove);
  23184. }
  23185. // Remove from the scene if mesh found
  23186. this.lights.splice(index, 1);
  23187. this.sortLightsByPriority();
  23188. }
  23189. this.onLightRemovedObservable.notifyObservers(toRemove);
  23190. return index;
  23191. };
  23192. Scene.prototype.removeCamera = function (toRemove) {
  23193. var index = this.cameras.indexOf(toRemove);
  23194. if (index !== -1) {
  23195. // Remove from the scene if mesh found
  23196. this.cameras.splice(index, 1);
  23197. }
  23198. // Remove from activeCameras
  23199. var index2 = this.activeCameras.indexOf(toRemove);
  23200. if (index2 !== -1) {
  23201. // Remove from the scene if mesh found
  23202. this.activeCameras.splice(index2, 1);
  23203. }
  23204. // Reset the activeCamera
  23205. if (this.activeCamera === toRemove) {
  23206. if (this.cameras.length > 0) {
  23207. this.activeCamera = this.cameras[0];
  23208. }
  23209. else {
  23210. this.activeCamera = null;
  23211. }
  23212. }
  23213. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23214. return index;
  23215. };
  23216. Scene.prototype.removeParticleSystem = function (toRemove) {
  23217. var index = this.particleSystems.indexOf(toRemove);
  23218. if (index !== -1) {
  23219. this.particleSystems.splice(index, 1);
  23220. }
  23221. return index;
  23222. };
  23223. ;
  23224. Scene.prototype.removeAnimation = function (toRemove) {
  23225. var index = this.animations.indexOf(toRemove);
  23226. if (index !== -1) {
  23227. this.animations.splice(index, 1);
  23228. }
  23229. return index;
  23230. };
  23231. ;
  23232. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23233. var index = this.multiMaterials.indexOf(toRemove);
  23234. if (index !== -1) {
  23235. this.multiMaterials.splice(index, 1);
  23236. }
  23237. return index;
  23238. };
  23239. ;
  23240. Scene.prototype.removeMaterial = function (toRemove) {
  23241. var index = this.materials.indexOf(toRemove);
  23242. if (index !== -1) {
  23243. this.materials.splice(index, 1);
  23244. }
  23245. return index;
  23246. };
  23247. ;
  23248. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23249. var index = this.lensFlareSystems.indexOf(toRemove);
  23250. if (index !== -1) {
  23251. this.lensFlareSystems.splice(index, 1);
  23252. }
  23253. return index;
  23254. };
  23255. ;
  23256. Scene.prototype.removeActionManager = function (toRemove) {
  23257. var index = this._actionManagers.indexOf(toRemove);
  23258. if (index !== -1) {
  23259. this._actionManagers.splice(index, 1);
  23260. }
  23261. return index;
  23262. };
  23263. ;
  23264. Scene.prototype.addLight = function (newLight) {
  23265. this.lights.push(newLight);
  23266. this.sortLightsByPriority();
  23267. // Add light to all meshes (To support if the light is removed and then readded)
  23268. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23269. var mesh = _a[_i];
  23270. if (mesh._lightSources.indexOf(newLight) === -1) {
  23271. mesh._lightSources.push(newLight);
  23272. mesh._resyncLightSources();
  23273. }
  23274. }
  23275. this.onNewLightAddedObservable.notifyObservers(newLight);
  23276. };
  23277. Scene.prototype.sortLightsByPriority = function () {
  23278. if (this.requireLightSorting) {
  23279. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23280. }
  23281. };
  23282. Scene.prototype.addCamera = function (newCamera) {
  23283. this.cameras.push(newCamera);
  23284. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23285. };
  23286. Scene.prototype.addSkeleton = function (newSkeleton) {
  23287. this.skeletons.push(newSkeleton);
  23288. };
  23289. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23290. this.particleSystems.push(newParticleSystem);
  23291. };
  23292. Scene.prototype.addAnimation = function (newAnimation) {
  23293. this.animations.push(newAnimation);
  23294. };
  23295. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23296. this.multiMaterials.push(newMultiMaterial);
  23297. };
  23298. Scene.prototype.addMaterial = function (newMaterial) {
  23299. this.materials.push(newMaterial);
  23300. };
  23301. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23302. this.morphTargetManagers.push(newMorphTargetManager);
  23303. };
  23304. Scene.prototype.addGeometry = function (newGeometrie) {
  23305. this._geometries.push(newGeometrie);
  23306. };
  23307. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23308. this.lensFlareSystems.push(newLensFlareSystem);
  23309. };
  23310. Scene.prototype.addActionManager = function (newActionManager) {
  23311. this._actionManagers.push(newActionManager);
  23312. };
  23313. /**
  23314. * Switch active camera
  23315. * @param {Camera} newCamera - new active camera
  23316. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23317. */
  23318. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23319. if (attachControl === void 0) { attachControl = true; }
  23320. var canvas = this._engine.getRenderingCanvas();
  23321. if (!canvas) {
  23322. return;
  23323. }
  23324. if (this.activeCamera) {
  23325. this.activeCamera.detachControl(canvas);
  23326. }
  23327. this.activeCamera = newCamera;
  23328. if (attachControl) {
  23329. newCamera.attachControl(canvas);
  23330. }
  23331. };
  23332. /**
  23333. * sets the active camera of the scene using its ID
  23334. * @param {string} id - the camera's ID
  23335. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23336. * @see activeCamera
  23337. */
  23338. Scene.prototype.setActiveCameraByID = function (id) {
  23339. var camera = this.getCameraByID(id);
  23340. if (camera) {
  23341. this.activeCamera = camera;
  23342. return camera;
  23343. }
  23344. return null;
  23345. };
  23346. /**
  23347. * sets the active camera of the scene using its name
  23348. * @param {string} name - the camera's name
  23349. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23350. * @see activeCamera
  23351. */
  23352. Scene.prototype.setActiveCameraByName = function (name) {
  23353. var camera = this.getCameraByName(name);
  23354. if (camera) {
  23355. this.activeCamera = camera;
  23356. return camera;
  23357. }
  23358. return null;
  23359. };
  23360. /**
  23361. * get an animation group using its name
  23362. * @param {string} the material's name
  23363. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23364. */
  23365. Scene.prototype.getAnimationGroupByName = function (name) {
  23366. for (var index = 0; index < this.animationGroups.length; index++) {
  23367. if (this.animationGroups[index].name === name) {
  23368. return this.animationGroups[index];
  23369. }
  23370. }
  23371. return null;
  23372. };
  23373. /**
  23374. * get a material using its id
  23375. * @param {string} the material's ID
  23376. * @return {BABYLON.Material|null} the material or null if none found.
  23377. */
  23378. Scene.prototype.getMaterialByID = function (id) {
  23379. for (var index = 0; index < this.materials.length; index++) {
  23380. if (this.materials[index].id === id) {
  23381. return this.materials[index];
  23382. }
  23383. }
  23384. return null;
  23385. };
  23386. /**
  23387. * get a material using its name
  23388. * @param {string} the material's name
  23389. * @return {BABYLON.Material|null} the material or null if none found.
  23390. */
  23391. Scene.prototype.getMaterialByName = function (name) {
  23392. for (var index = 0; index < this.materials.length; index++) {
  23393. if (this.materials[index].name === name) {
  23394. return this.materials[index];
  23395. }
  23396. }
  23397. return null;
  23398. };
  23399. Scene.prototype.getLensFlareSystemByName = function (name) {
  23400. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23401. if (this.lensFlareSystems[index].name === name) {
  23402. return this.lensFlareSystems[index];
  23403. }
  23404. }
  23405. return null;
  23406. };
  23407. Scene.prototype.getLensFlareSystemByID = function (id) {
  23408. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23409. if (this.lensFlareSystems[index].id === id) {
  23410. return this.lensFlareSystems[index];
  23411. }
  23412. }
  23413. return null;
  23414. };
  23415. Scene.prototype.getCameraByID = function (id) {
  23416. for (var index = 0; index < this.cameras.length; index++) {
  23417. if (this.cameras[index].id === id) {
  23418. return this.cameras[index];
  23419. }
  23420. }
  23421. return null;
  23422. };
  23423. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23424. for (var index = 0; index < this.cameras.length; index++) {
  23425. if (this.cameras[index].uniqueId === uniqueId) {
  23426. return this.cameras[index];
  23427. }
  23428. }
  23429. return null;
  23430. };
  23431. /**
  23432. * get a camera using its name
  23433. * @param {string} the camera's name
  23434. * @return {BABYLON.Camera|null} the camera or null if none found.
  23435. */
  23436. Scene.prototype.getCameraByName = function (name) {
  23437. for (var index = 0; index < this.cameras.length; index++) {
  23438. if (this.cameras[index].name === name) {
  23439. return this.cameras[index];
  23440. }
  23441. }
  23442. return null;
  23443. };
  23444. /**
  23445. * get a bone using its id
  23446. * @param {string} the bone's id
  23447. * @return {BABYLON.Bone|null} the bone or null if not found
  23448. */
  23449. Scene.prototype.getBoneByID = function (id) {
  23450. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23451. var skeleton = this.skeletons[skeletonIndex];
  23452. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23453. if (skeleton.bones[boneIndex].id === id) {
  23454. return skeleton.bones[boneIndex];
  23455. }
  23456. }
  23457. }
  23458. return null;
  23459. };
  23460. /**
  23461. * get a bone using its id
  23462. * @param {string} the bone's name
  23463. * @return {BABYLON.Bone|null} the bone or null if not found
  23464. */
  23465. Scene.prototype.getBoneByName = function (name) {
  23466. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23467. var skeleton = this.skeletons[skeletonIndex];
  23468. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23469. if (skeleton.bones[boneIndex].name === name) {
  23470. return skeleton.bones[boneIndex];
  23471. }
  23472. }
  23473. }
  23474. return null;
  23475. };
  23476. /**
  23477. * get a light node using its name
  23478. * @param {string} the light's name
  23479. * @return {BABYLON.Light|null} the light or null if none found.
  23480. */
  23481. Scene.prototype.getLightByName = function (name) {
  23482. for (var index = 0; index < this.lights.length; index++) {
  23483. if (this.lights[index].name === name) {
  23484. return this.lights[index];
  23485. }
  23486. }
  23487. return null;
  23488. };
  23489. /**
  23490. * get a light node using its ID
  23491. * @param {string} the light's id
  23492. * @return {BABYLON.Light|null} the light or null if none found.
  23493. */
  23494. Scene.prototype.getLightByID = function (id) {
  23495. for (var index = 0; index < this.lights.length; index++) {
  23496. if (this.lights[index].id === id) {
  23497. return this.lights[index];
  23498. }
  23499. }
  23500. return null;
  23501. };
  23502. /**
  23503. * get a light node using its scene-generated unique ID
  23504. * @param {number} the light's unique id
  23505. * @return {BABYLON.Light|null} the light or null if none found.
  23506. */
  23507. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23508. for (var index = 0; index < this.lights.length; index++) {
  23509. if (this.lights[index].uniqueId === uniqueId) {
  23510. return this.lights[index];
  23511. }
  23512. }
  23513. return null;
  23514. };
  23515. /**
  23516. * get a particle system by id
  23517. * @param id {number} the particle system id
  23518. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23519. */
  23520. Scene.prototype.getParticleSystemByID = function (id) {
  23521. for (var index = 0; index < this.particleSystems.length; index++) {
  23522. if (this.particleSystems[index].id === id) {
  23523. return this.particleSystems[index];
  23524. }
  23525. }
  23526. return null;
  23527. };
  23528. /**
  23529. * get a geometry using its ID
  23530. * @param {string} the geometry's id
  23531. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23532. */
  23533. Scene.prototype.getGeometryByID = function (id) {
  23534. for (var index = 0; index < this._geometries.length; index++) {
  23535. if (this._geometries[index].id === id) {
  23536. return this._geometries[index];
  23537. }
  23538. }
  23539. return null;
  23540. };
  23541. /**
  23542. * add a new geometry to this scene.
  23543. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23544. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23545. * @return {boolean} was the geometry added or not
  23546. */
  23547. Scene.prototype.pushGeometry = function (geometry, force) {
  23548. if (!force && this.getGeometryByID(geometry.id)) {
  23549. return false;
  23550. }
  23551. this._geometries.push(geometry);
  23552. //notify the collision coordinator
  23553. if (this.collisionCoordinator) {
  23554. this.collisionCoordinator.onGeometryAdded(geometry);
  23555. }
  23556. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23557. return true;
  23558. };
  23559. /**
  23560. * Removes an existing geometry
  23561. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23562. * @return {boolean} was the geometry removed or not
  23563. */
  23564. Scene.prototype.removeGeometry = function (geometry) {
  23565. var index = this._geometries.indexOf(geometry);
  23566. if (index > -1) {
  23567. this._geometries.splice(index, 1);
  23568. //notify the collision coordinator
  23569. if (this.collisionCoordinator) {
  23570. this.collisionCoordinator.onGeometryDeleted(geometry);
  23571. }
  23572. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23573. return true;
  23574. }
  23575. return false;
  23576. };
  23577. Scene.prototype.getGeometries = function () {
  23578. return this._geometries;
  23579. };
  23580. /**
  23581. * Get the first added mesh found of a given ID
  23582. * @param {string} id - the id to search for
  23583. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23584. */
  23585. Scene.prototype.getMeshByID = function (id) {
  23586. for (var index = 0; index < this.meshes.length; index++) {
  23587. if (this.meshes[index].id === id) {
  23588. return this.meshes[index];
  23589. }
  23590. }
  23591. return null;
  23592. };
  23593. Scene.prototype.getMeshesByID = function (id) {
  23594. return this.meshes.filter(function (m) {
  23595. return m.id === id;
  23596. });
  23597. };
  23598. /**
  23599. * Get the first added transform node found of a given ID
  23600. * @param {string} id - the id to search for
  23601. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23602. */
  23603. Scene.prototype.getTransformNodeByID = function (id) {
  23604. for (var index = 0; index < this.transformNodes.length; index++) {
  23605. if (this.transformNodes[index].id === id) {
  23606. return this.transformNodes[index];
  23607. }
  23608. }
  23609. return null;
  23610. };
  23611. Scene.prototype.getTransformNodesByID = function (id) {
  23612. return this.transformNodes.filter(function (m) {
  23613. return m.id === id;
  23614. });
  23615. };
  23616. /**
  23617. * Get a mesh with its auto-generated unique id
  23618. * @param {number} uniqueId - the unique id to search for
  23619. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23620. */
  23621. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23622. for (var index = 0; index < this.meshes.length; index++) {
  23623. if (this.meshes[index].uniqueId === uniqueId) {
  23624. return this.meshes[index];
  23625. }
  23626. }
  23627. return null;
  23628. };
  23629. /**
  23630. * Get a the last added mesh found of a given ID
  23631. * @param {string} id - the id to search for
  23632. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23633. */
  23634. Scene.prototype.getLastMeshByID = function (id) {
  23635. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23636. if (this.meshes[index].id === id) {
  23637. return this.meshes[index];
  23638. }
  23639. }
  23640. return null;
  23641. };
  23642. /**
  23643. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23644. * @param {string} id - the id to search for
  23645. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23646. */
  23647. Scene.prototype.getLastEntryByID = function (id) {
  23648. var index;
  23649. for (index = this.meshes.length - 1; index >= 0; index--) {
  23650. if (this.meshes[index].id === id) {
  23651. return this.meshes[index];
  23652. }
  23653. }
  23654. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23655. if (this.transformNodes[index].id === id) {
  23656. return this.transformNodes[index];
  23657. }
  23658. }
  23659. for (index = this.cameras.length - 1; index >= 0; index--) {
  23660. if (this.cameras[index].id === id) {
  23661. return this.cameras[index];
  23662. }
  23663. }
  23664. for (index = this.lights.length - 1; index >= 0; index--) {
  23665. if (this.lights[index].id === id) {
  23666. return this.lights[index];
  23667. }
  23668. }
  23669. return null;
  23670. };
  23671. Scene.prototype.getNodeByID = function (id) {
  23672. var mesh = this.getMeshByID(id);
  23673. if (mesh) {
  23674. return mesh;
  23675. }
  23676. var light = this.getLightByID(id);
  23677. if (light) {
  23678. return light;
  23679. }
  23680. var camera = this.getCameraByID(id);
  23681. if (camera) {
  23682. return camera;
  23683. }
  23684. var bone = this.getBoneByID(id);
  23685. return bone;
  23686. };
  23687. Scene.prototype.getNodeByName = function (name) {
  23688. var mesh = this.getMeshByName(name);
  23689. if (mesh) {
  23690. return mesh;
  23691. }
  23692. var light = this.getLightByName(name);
  23693. if (light) {
  23694. return light;
  23695. }
  23696. var camera = this.getCameraByName(name);
  23697. if (camera) {
  23698. return camera;
  23699. }
  23700. var bone = this.getBoneByName(name);
  23701. return bone;
  23702. };
  23703. Scene.prototype.getMeshByName = function (name) {
  23704. for (var index = 0; index < this.meshes.length; index++) {
  23705. if (this.meshes[index].name === name) {
  23706. return this.meshes[index];
  23707. }
  23708. }
  23709. return null;
  23710. };
  23711. Scene.prototype.getTransformNodeByName = function (name) {
  23712. for (var index = 0; index < this.transformNodes.length; index++) {
  23713. if (this.transformNodes[index].name === name) {
  23714. return this.transformNodes[index];
  23715. }
  23716. }
  23717. return null;
  23718. };
  23719. Scene.prototype.getSoundByName = function (name) {
  23720. var index;
  23721. if (BABYLON.AudioEngine) {
  23722. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23723. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23724. return this.mainSoundTrack.soundCollection[index];
  23725. }
  23726. }
  23727. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23728. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23729. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23730. return this.soundTracks[sdIndex].soundCollection[index];
  23731. }
  23732. }
  23733. }
  23734. }
  23735. return null;
  23736. };
  23737. Scene.prototype.getLastSkeletonByID = function (id) {
  23738. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23739. if (this.skeletons[index].id === id) {
  23740. return this.skeletons[index];
  23741. }
  23742. }
  23743. return null;
  23744. };
  23745. Scene.prototype.getSkeletonById = function (id) {
  23746. for (var index = 0; index < this.skeletons.length; index++) {
  23747. if (this.skeletons[index].id === id) {
  23748. return this.skeletons[index];
  23749. }
  23750. }
  23751. return null;
  23752. };
  23753. Scene.prototype.getSkeletonByName = function (name) {
  23754. for (var index = 0; index < this.skeletons.length; index++) {
  23755. if (this.skeletons[index].name === name) {
  23756. return this.skeletons[index];
  23757. }
  23758. }
  23759. return null;
  23760. };
  23761. Scene.prototype.getMorphTargetManagerById = function (id) {
  23762. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23763. if (this.morphTargetManagers[index].uniqueId === id) {
  23764. return this.morphTargetManagers[index];
  23765. }
  23766. }
  23767. return null;
  23768. };
  23769. Scene.prototype.isActiveMesh = function (mesh) {
  23770. return (this._activeMeshes.indexOf(mesh) !== -1);
  23771. };
  23772. /**
  23773. * Return a the first highlight layer of the scene with a given name.
  23774. * @param name The name of the highlight layer to look for.
  23775. * @return The highlight layer if found otherwise null.
  23776. */
  23777. Scene.prototype.getHighlightLayerByName = function (name) {
  23778. for (var index = 0; index < this.effectLayers.length; index++) {
  23779. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23780. return this.effectLayers[index];
  23781. }
  23782. }
  23783. return null;
  23784. };
  23785. /**
  23786. * Return a the first highlight layer of the scene with a given name.
  23787. * @param name The name of the highlight layer to look for.
  23788. * @return The highlight layer if found otherwise null.
  23789. */
  23790. Scene.prototype.getGlowLayerByName = function (name) {
  23791. for (var index = 0; index < this.effectLayers.length; index++) {
  23792. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23793. return this.effectLayers[index];
  23794. }
  23795. }
  23796. return null;
  23797. };
  23798. Object.defineProperty(Scene.prototype, "uid", {
  23799. /**
  23800. * Return a unique id as a string which can serve as an identifier for the scene
  23801. */
  23802. get: function () {
  23803. if (!this._uid) {
  23804. this._uid = BABYLON.Tools.RandomId();
  23805. }
  23806. return this._uid;
  23807. },
  23808. enumerable: true,
  23809. configurable: true
  23810. });
  23811. /**
  23812. * Add an externaly attached data from its key.
  23813. * This method call will fail and return false, if such key already exists.
  23814. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23815. * @param key the unique key that identifies the data
  23816. * @param data the data object to associate to the key for this Engine instance
  23817. * @return true if no such key were already present and the data was added successfully, false otherwise
  23818. */
  23819. Scene.prototype.addExternalData = function (key, data) {
  23820. if (!this._externalData) {
  23821. this._externalData = new BABYLON.StringDictionary();
  23822. }
  23823. return this._externalData.add(key, data);
  23824. };
  23825. /**
  23826. * Get an externaly attached data from its key
  23827. * @param key the unique key that identifies the data
  23828. * @return the associated data, if present (can be null), or undefined if not present
  23829. */
  23830. Scene.prototype.getExternalData = function (key) {
  23831. if (!this._externalData) {
  23832. return null;
  23833. }
  23834. return this._externalData.get(key);
  23835. };
  23836. /**
  23837. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23838. * @param key the unique key that identifies the data
  23839. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23840. * @return the associated data, can be null if the factory returned null.
  23841. */
  23842. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23843. if (!this._externalData) {
  23844. this._externalData = new BABYLON.StringDictionary();
  23845. }
  23846. return this._externalData.getOrAddWithFactory(key, factory);
  23847. };
  23848. /**
  23849. * Remove an externaly attached data from the Engine instance
  23850. * @param key the unique key that identifies the data
  23851. * @return true if the data was successfully removed, false if it doesn't exist
  23852. */
  23853. Scene.prototype.removeExternalData = function (key) {
  23854. return this._externalData.remove(key);
  23855. };
  23856. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23857. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23858. if (mesh.showSubMeshesBoundingBox) {
  23859. var boundingInfo = subMesh.getBoundingInfo();
  23860. if (boundingInfo !== null && boundingInfo !== undefined) {
  23861. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23862. }
  23863. }
  23864. var material = subMesh.getMaterial();
  23865. if (material !== null && material !== undefined) {
  23866. // Render targets
  23867. if (material.getRenderTargetTextures !== undefined) {
  23868. if (this._processedMaterials.indexOf(material) === -1) {
  23869. this._processedMaterials.push(material);
  23870. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23871. }
  23872. }
  23873. // Dispatch
  23874. this._activeIndices.addCount(subMesh.indexCount, false);
  23875. this._renderingManager.dispatch(subMesh, mesh, material);
  23876. }
  23877. }
  23878. };
  23879. Scene.prototype._isInIntermediateRendering = function () {
  23880. return this._intermediateRendering;
  23881. };
  23882. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23883. this._activeMeshCandidateProvider = provider;
  23884. };
  23885. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23886. return this._activeMeshCandidateProvider;
  23887. };
  23888. /**
  23889. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23890. */
  23891. Scene.prototype.freezeActiveMeshes = function () {
  23892. this._evaluateActiveMeshes();
  23893. this._activeMeshesFrozen = true;
  23894. return this;
  23895. };
  23896. /**
  23897. * Use this function to restart evaluating active meshes on every frame
  23898. */
  23899. Scene.prototype.unfreezeActiveMeshes = function () {
  23900. this._activeMeshesFrozen = false;
  23901. return this;
  23902. };
  23903. Scene.prototype._evaluateActiveMeshes = function () {
  23904. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23905. return;
  23906. }
  23907. if (!this.activeCamera) {
  23908. return;
  23909. }
  23910. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23911. this.activeCamera._activeMeshes.reset();
  23912. this._activeMeshes.reset();
  23913. this._renderingManager.reset();
  23914. this._processedMaterials.reset();
  23915. this._activeParticleSystems.reset();
  23916. this._activeSkeletons.reset();
  23917. this._softwareSkinnedMeshes.reset();
  23918. if (this._boundingBoxRenderer) {
  23919. this._boundingBoxRenderer.reset();
  23920. }
  23921. // Meshes
  23922. var meshes;
  23923. var len;
  23924. var checkIsEnabled = true;
  23925. // Determine mesh candidates
  23926. if (this._activeMeshCandidateProvider !== undefined) {
  23927. // Use _activeMeshCandidateProvider
  23928. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23929. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23930. if (meshes !== undefined) {
  23931. len = meshes.length;
  23932. }
  23933. else {
  23934. len = 0;
  23935. }
  23936. }
  23937. else if (this._selectionOctree !== undefined) {
  23938. // Octree
  23939. var selection = this._selectionOctree.select(this._frustumPlanes);
  23940. meshes = selection.data;
  23941. len = selection.length;
  23942. }
  23943. else {
  23944. // Full scene traversal
  23945. len = this.meshes.length;
  23946. meshes = this.meshes;
  23947. }
  23948. // Check each mesh
  23949. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23950. mesh = meshes[meshIndex];
  23951. if (mesh.isBlocked) {
  23952. continue;
  23953. }
  23954. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23955. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23956. continue;
  23957. }
  23958. mesh.computeWorldMatrix();
  23959. // Intersections
  23960. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23961. this._meshesForIntersections.pushNoDuplicate(mesh);
  23962. }
  23963. // Switch to current LOD
  23964. meshLOD = mesh.getLOD(this.activeCamera);
  23965. if (meshLOD === undefined || meshLOD === null) {
  23966. continue;
  23967. }
  23968. mesh._preActivate();
  23969. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23970. this._activeMeshes.push(mesh);
  23971. this.activeCamera._activeMeshes.push(mesh);
  23972. mesh._activate(this._renderId);
  23973. if (meshLOD !== mesh) {
  23974. meshLOD._activate(this._renderId);
  23975. }
  23976. this._activeMesh(mesh, meshLOD);
  23977. }
  23978. }
  23979. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23980. // Particle systems
  23981. if (this.particlesEnabled) {
  23982. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23983. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23984. var particleSystem = this.particleSystems[particleIndex];
  23985. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23986. continue;
  23987. }
  23988. var emitter = particleSystem.emitter;
  23989. if (!emitter.position || emitter.isEnabled()) {
  23990. this._activeParticleSystems.push(particleSystem);
  23991. particleSystem.animate();
  23992. this._renderingManager.dispatchParticles(particleSystem);
  23993. }
  23994. }
  23995. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23996. }
  23997. };
  23998. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23999. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24000. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24001. mesh.skeleton.prepare();
  24002. }
  24003. if (!mesh.computeBonesUsingShaders) {
  24004. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24005. }
  24006. }
  24007. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24008. var boundingInfo = sourceMesh.getBoundingInfo();
  24009. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24010. }
  24011. if (mesh !== undefined && mesh !== null
  24012. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24013. // Submeshes Octrees
  24014. var len;
  24015. var subMeshes;
  24016. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24017. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24018. len = intersections.length;
  24019. subMeshes = intersections.data;
  24020. }
  24021. else {
  24022. subMeshes = mesh.subMeshes;
  24023. len = subMeshes.length;
  24024. }
  24025. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24026. subMesh = subMeshes[subIndex];
  24027. this._evaluateSubMesh(subMesh, mesh);
  24028. }
  24029. }
  24030. };
  24031. Scene.prototype.updateTransformMatrix = function (force) {
  24032. if (!this.activeCamera) {
  24033. return;
  24034. }
  24035. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24036. };
  24037. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24038. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24039. };
  24040. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24041. if (camera && camera._skipRendering) {
  24042. return;
  24043. }
  24044. var engine = this._engine;
  24045. this.activeCamera = camera;
  24046. if (!this.activeCamera)
  24047. throw new Error("Active camera not set");
  24048. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24049. // Viewport
  24050. engine.setViewport(this.activeCamera.viewport);
  24051. // Camera
  24052. this.resetCachedMaterial();
  24053. this._renderId++;
  24054. this.updateTransformMatrix();
  24055. if (camera._alternateCamera) {
  24056. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24057. this._alternateRendering = true;
  24058. }
  24059. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24060. // Meshes
  24061. this._evaluateActiveMeshes();
  24062. // Software skinning
  24063. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24064. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24065. mesh.applySkeleton(mesh.skeleton);
  24066. }
  24067. // Render targets
  24068. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24069. var needsRestoreFrameBuffer = false;
  24070. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24071. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24072. }
  24073. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24074. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24075. }
  24076. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24077. this._intermediateRendering = true;
  24078. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24079. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24080. var renderTarget = this._renderTargets.data[renderIndex];
  24081. if (renderTarget._shouldRender()) {
  24082. this._renderId++;
  24083. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24084. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24085. }
  24086. }
  24087. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24088. this._intermediateRendering = false;
  24089. this._renderId++;
  24090. needsRestoreFrameBuffer = true; // Restore back buffer
  24091. }
  24092. // Render EffecttLayer Texture
  24093. var stencilState = this._engine.getStencilBuffer();
  24094. var renderEffects = false;
  24095. var needStencil = false;
  24096. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24097. this._intermediateRendering = true;
  24098. for (var i = 0; i < this.effectLayers.length; i++) {
  24099. var effectLayer = this.effectLayers[i];
  24100. if (effectLayer.shouldRender() &&
  24101. (!effectLayer.camera ||
  24102. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24103. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24104. renderEffects = true;
  24105. needStencil = needStencil || effectLayer.needStencil();
  24106. var renderTarget = effectLayer._mainTexture;
  24107. if (renderTarget._shouldRender()) {
  24108. this._renderId++;
  24109. renderTarget.render(false, false);
  24110. needsRestoreFrameBuffer = true;
  24111. }
  24112. }
  24113. }
  24114. this._intermediateRendering = false;
  24115. this._renderId++;
  24116. }
  24117. if (needsRestoreFrameBuffer) {
  24118. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24119. }
  24120. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24121. // Prepare Frame
  24122. this.postProcessManager._prepareFrame();
  24123. // Backgrounds
  24124. var layerIndex;
  24125. var layer;
  24126. if (this.layers.length) {
  24127. engine.setDepthBuffer(false);
  24128. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24129. layer = this.layers[layerIndex];
  24130. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24131. layer.render();
  24132. }
  24133. }
  24134. engine.setDepthBuffer(true);
  24135. }
  24136. // Activate effect Layer stencil
  24137. if (needStencil) {
  24138. this._engine.setStencilBuffer(true);
  24139. }
  24140. // Render
  24141. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24142. this._renderingManager.render(null, null, true, true);
  24143. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24144. // Restore effect Layer stencil
  24145. if (needStencil) {
  24146. this._engine.setStencilBuffer(stencilState);
  24147. }
  24148. // Bounding boxes
  24149. if (this._boundingBoxRenderer) {
  24150. this._boundingBoxRenderer.render();
  24151. }
  24152. // Lens flares
  24153. if (this.lensFlaresEnabled) {
  24154. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24155. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24156. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24157. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24158. lensFlareSystem.render();
  24159. }
  24160. }
  24161. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24162. }
  24163. // Foregrounds
  24164. if (this.layers.length) {
  24165. engine.setDepthBuffer(false);
  24166. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24167. layer = this.layers[layerIndex];
  24168. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24169. layer.render();
  24170. }
  24171. }
  24172. engine.setDepthBuffer(true);
  24173. }
  24174. // Effect Layer
  24175. if (renderEffects) {
  24176. engine.setDepthBuffer(false);
  24177. for (var i = 0; i < this.effectLayers.length; i++) {
  24178. if (this.effectLayers[i].shouldRender()) {
  24179. this.effectLayers[i].render();
  24180. }
  24181. }
  24182. engine.setDepthBuffer(true);
  24183. }
  24184. // Finalize frame
  24185. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24186. // Reset some special arrays
  24187. this._renderTargets.reset();
  24188. this._alternateRendering = false;
  24189. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24190. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24191. };
  24192. Scene.prototype._processSubCameras = function (camera) {
  24193. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24194. this._renderForCamera(camera);
  24195. return;
  24196. }
  24197. // rig cameras
  24198. for (var index = 0; index < camera._rigCameras.length; index++) {
  24199. this._renderForCamera(camera._rigCameras[index], camera);
  24200. }
  24201. this.activeCamera = camera;
  24202. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24203. };
  24204. Scene.prototype._checkIntersections = function () {
  24205. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24206. var sourceMesh = this._meshesForIntersections.data[index];
  24207. if (!sourceMesh.actionManager) {
  24208. continue;
  24209. }
  24210. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24211. var action = sourceMesh.actionManager.actions[actionIndex];
  24212. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24213. var parameters = action.getTriggerParameter();
  24214. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24215. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24216. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24217. if (areIntersecting && currentIntersectionInProgress === -1) {
  24218. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24219. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24220. sourceMesh._intersectionsInProgress.push(otherMesh);
  24221. }
  24222. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24223. sourceMesh._intersectionsInProgress.push(otherMesh);
  24224. }
  24225. }
  24226. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24227. //They intersected, and now they don't.
  24228. //is this trigger an exit trigger? execute an event.
  24229. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24230. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24231. }
  24232. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24233. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24234. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24235. }
  24236. }
  24237. }
  24238. }
  24239. }
  24240. };
  24241. Scene.prototype.render = function () {
  24242. if (this.isDisposed) {
  24243. return;
  24244. }
  24245. this._activeParticles.fetchNewFrame();
  24246. this._totalVertices.fetchNewFrame();
  24247. this._activeIndices.fetchNewFrame();
  24248. this._activeBones.fetchNewFrame();
  24249. this._meshesForIntersections.reset();
  24250. this.resetCachedMaterial();
  24251. this.onBeforeAnimationsObservable.notifyObservers(this);
  24252. // Actions
  24253. if (this.actionManager) {
  24254. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24255. }
  24256. //Simplification Queue
  24257. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24258. this.simplificationQueue.executeNext();
  24259. }
  24260. if (this._engine.isDeterministicLockStep()) {
  24261. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24262. var defaultFPS = (60.0 / 1000.0);
  24263. var defaultFrameTime = 1000 / 60; // frame time in MS
  24264. if (this._physicsEngine) {
  24265. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24266. }
  24267. var stepsTaken = 0;
  24268. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24269. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24270. internalSteps = Math.min(internalSteps, maxSubSteps);
  24271. do {
  24272. this.onBeforeStepObservable.notifyObservers(this);
  24273. // Animations
  24274. this._animationRatio = defaultFrameTime * defaultFPS;
  24275. this._animate();
  24276. this.onAfterAnimationsObservable.notifyObservers(this);
  24277. // Physics
  24278. if (this._physicsEngine) {
  24279. this.onBeforePhysicsObservable.notifyObservers(this);
  24280. this._physicsEngine._step(defaultFrameTime / 1000);
  24281. this.onAfterPhysicsObservable.notifyObservers(this);
  24282. }
  24283. this.onAfterStepObservable.notifyObservers(this);
  24284. this._currentStepId++;
  24285. stepsTaken++;
  24286. deltaTime -= defaultFrameTime;
  24287. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24288. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24289. }
  24290. else {
  24291. // Animations
  24292. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24293. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24294. this._animate();
  24295. this.onAfterAnimationsObservable.notifyObservers(this);
  24296. // Physics
  24297. if (this._physicsEngine) {
  24298. this.onBeforePhysicsObservable.notifyObservers(this);
  24299. this._physicsEngine._step(deltaTime / 1000.0);
  24300. this.onAfterPhysicsObservable.notifyObservers(this);
  24301. }
  24302. }
  24303. // update gamepad manager
  24304. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24305. this._gamepadManager._checkGamepadsStatus();
  24306. }
  24307. // Before render
  24308. this.onBeforeRenderObservable.notifyObservers(this);
  24309. // Update Cameras
  24310. if (this.activeCameras.length > 0) {
  24311. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24312. var camera = this.activeCameras[cameraIndex];
  24313. camera.update();
  24314. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24315. // rig cameras
  24316. for (var index = 0; index < camera._rigCameras.length; index++) {
  24317. camera._rigCameras[index].update();
  24318. }
  24319. }
  24320. }
  24321. }
  24322. else if (this.activeCamera) {
  24323. this.activeCamera.update();
  24324. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24325. // rig cameras
  24326. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24327. this.activeCamera._rigCameras[index].update();
  24328. }
  24329. }
  24330. }
  24331. // Customs render targets
  24332. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24333. var engine = this.getEngine();
  24334. var currentActiveCamera = this.activeCamera;
  24335. if (this.renderTargetsEnabled) {
  24336. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24337. this._intermediateRendering = true;
  24338. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24339. var renderTarget = this.customRenderTargets[customIndex];
  24340. if (renderTarget._shouldRender()) {
  24341. this._renderId++;
  24342. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24343. if (!this.activeCamera)
  24344. throw new Error("Active camera not set");
  24345. // Viewport
  24346. engine.setViewport(this.activeCamera.viewport);
  24347. // Camera
  24348. this.updateTransformMatrix();
  24349. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24350. }
  24351. }
  24352. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24353. this._intermediateRendering = false;
  24354. this._renderId++;
  24355. }
  24356. // Restore back buffer
  24357. if (this.customRenderTargets.length > 0) {
  24358. engine.restoreDefaultFramebuffer();
  24359. }
  24360. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24361. this.activeCamera = currentActiveCamera;
  24362. // Procedural textures
  24363. if (this.proceduralTexturesEnabled) {
  24364. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24365. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24366. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24367. if (proceduralTexture._shouldRender()) {
  24368. proceduralTexture.render();
  24369. }
  24370. }
  24371. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24372. }
  24373. // Clear
  24374. if (this.autoClearDepthAndStencil || this.autoClear) {
  24375. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24376. }
  24377. // Shadows
  24378. if (this.shadowsEnabled) {
  24379. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24380. var light = this.lights[lightIndex];
  24381. var shadowGenerator = light.getShadowGenerator();
  24382. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24383. var shadowMap = (shadowGenerator.getShadowMap());
  24384. if (this.textures.indexOf(shadowMap) !== -1) {
  24385. this._renderTargets.push(shadowMap);
  24386. }
  24387. }
  24388. }
  24389. }
  24390. // Depth renderer
  24391. for (var key in this._depthRenderer) {
  24392. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24393. }
  24394. // Geometry renderer
  24395. if (this._geometryBufferRenderer) {
  24396. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24397. }
  24398. // RenderPipeline
  24399. if (this._postProcessRenderPipelineManager) {
  24400. this._postProcessRenderPipelineManager.update();
  24401. }
  24402. // Multi-cameras?
  24403. if (this.activeCameras.length > 0) {
  24404. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24405. if (cameraIndex > 0) {
  24406. this._engine.clear(null, false, true, true);
  24407. }
  24408. this._processSubCameras(this.activeCameras[cameraIndex]);
  24409. }
  24410. }
  24411. else {
  24412. if (!this.activeCamera) {
  24413. throw new Error("No camera defined");
  24414. }
  24415. this._processSubCameras(this.activeCamera);
  24416. }
  24417. // Intersection checks
  24418. this._checkIntersections();
  24419. // Update the audio listener attached to the camera
  24420. if (BABYLON.AudioEngine) {
  24421. this._updateAudioParameters();
  24422. }
  24423. // After render
  24424. if (this.afterRender) {
  24425. this.afterRender();
  24426. }
  24427. this.onAfterRenderObservable.notifyObservers(this);
  24428. // Cleaning
  24429. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24430. var data = this._toBeDisposed.data[index];
  24431. if (data) {
  24432. data.dispose();
  24433. }
  24434. this._toBeDisposed[index] = null;
  24435. }
  24436. this._toBeDisposed.reset();
  24437. if (this.dumpNextRenderTargets) {
  24438. this.dumpNextRenderTargets = false;
  24439. }
  24440. this._activeBones.addCount(0, true);
  24441. this._activeIndices.addCount(0, true);
  24442. this._activeParticles.addCount(0, true);
  24443. };
  24444. Scene.prototype._updateAudioParameters = function () {
  24445. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24446. return;
  24447. }
  24448. var listeningCamera;
  24449. var audioEngine = BABYLON.Engine.audioEngine;
  24450. if (this.activeCameras.length > 0) {
  24451. listeningCamera = this.activeCameras[0];
  24452. }
  24453. else {
  24454. listeningCamera = this.activeCamera;
  24455. }
  24456. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24457. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24458. // for VR cameras
  24459. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24460. listeningCamera = listeningCamera.rigCameras[0];
  24461. }
  24462. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24463. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24464. cameraDirection.normalize();
  24465. // To avoid some errors on GearVR
  24466. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24467. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24468. }
  24469. var i;
  24470. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24471. var sound = this.mainSoundTrack.soundCollection[i];
  24472. if (sound.useCustomAttenuation) {
  24473. sound.updateDistanceFromListener();
  24474. }
  24475. }
  24476. for (i = 0; i < this.soundTracks.length; i++) {
  24477. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24478. sound = this.soundTracks[i].soundCollection[j];
  24479. if (sound.useCustomAttenuation) {
  24480. sound.updateDistanceFromListener();
  24481. }
  24482. }
  24483. }
  24484. }
  24485. };
  24486. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24487. // Audio
  24488. get: function () {
  24489. return this._audioEnabled;
  24490. },
  24491. set: function (value) {
  24492. this._audioEnabled = value;
  24493. if (BABYLON.AudioEngine) {
  24494. if (this._audioEnabled) {
  24495. this._enableAudio();
  24496. }
  24497. else {
  24498. this._disableAudio();
  24499. }
  24500. }
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Scene.prototype._disableAudio = function () {
  24506. var i;
  24507. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24508. this.mainSoundTrack.soundCollection[i].pause();
  24509. }
  24510. for (i = 0; i < this.soundTracks.length; i++) {
  24511. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24512. this.soundTracks[i].soundCollection[j].pause();
  24513. }
  24514. }
  24515. };
  24516. Scene.prototype._enableAudio = function () {
  24517. var i;
  24518. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24519. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24520. this.mainSoundTrack.soundCollection[i].play();
  24521. }
  24522. }
  24523. for (i = 0; i < this.soundTracks.length; i++) {
  24524. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24525. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24526. this.soundTracks[i].soundCollection[j].play();
  24527. }
  24528. }
  24529. }
  24530. };
  24531. Object.defineProperty(Scene.prototype, "headphone", {
  24532. get: function () {
  24533. return this._headphone;
  24534. },
  24535. set: function (value) {
  24536. this._headphone = value;
  24537. if (BABYLON.AudioEngine) {
  24538. if (this._headphone) {
  24539. this._switchAudioModeForHeadphones();
  24540. }
  24541. else {
  24542. this._switchAudioModeForNormalSpeakers();
  24543. }
  24544. }
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. Scene.prototype._switchAudioModeForHeadphones = function () {
  24550. this.mainSoundTrack.switchPanningModelToHRTF();
  24551. for (var i = 0; i < this.soundTracks.length; i++) {
  24552. this.soundTracks[i].switchPanningModelToHRTF();
  24553. }
  24554. };
  24555. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24556. this.mainSoundTrack.switchPanningModelToEqualPower();
  24557. for (var i = 0; i < this.soundTracks.length; i++) {
  24558. this.soundTracks[i].switchPanningModelToEqualPower();
  24559. }
  24560. };
  24561. /**
  24562. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24563. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24564. * @returns the created depth renderer
  24565. */
  24566. Scene.prototype.enableDepthRenderer = function (camera) {
  24567. camera = camera || this.activeCamera;
  24568. if (!camera) {
  24569. throw "No camera available to enable depth renderer";
  24570. }
  24571. if (!this._depthRenderer[camera.id]) {
  24572. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24573. }
  24574. return this._depthRenderer[camera.id];
  24575. };
  24576. /**
  24577. * Disables a depth renderer for a given camera
  24578. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24579. */
  24580. Scene.prototype.disableDepthRenderer = function (camera) {
  24581. camera = camera || this.activeCamera;
  24582. if (!camera || !this._depthRenderer[camera.id]) {
  24583. return;
  24584. }
  24585. this._depthRenderer[camera.id].dispose();
  24586. delete this._depthRenderer[camera.id];
  24587. };
  24588. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24589. if (ratio === void 0) { ratio = 1; }
  24590. if (this._geometryBufferRenderer) {
  24591. return this._geometryBufferRenderer;
  24592. }
  24593. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24594. if (!this._geometryBufferRenderer.isSupported) {
  24595. this._geometryBufferRenderer = null;
  24596. }
  24597. return this._geometryBufferRenderer;
  24598. };
  24599. Scene.prototype.disableGeometryBufferRenderer = function () {
  24600. if (!this._geometryBufferRenderer) {
  24601. return;
  24602. }
  24603. this._geometryBufferRenderer.dispose();
  24604. this._geometryBufferRenderer = null;
  24605. };
  24606. Scene.prototype.freezeMaterials = function () {
  24607. for (var i = 0; i < this.materials.length; i++) {
  24608. this.materials[i].freeze();
  24609. }
  24610. };
  24611. Scene.prototype.unfreezeMaterials = function () {
  24612. for (var i = 0; i < this.materials.length; i++) {
  24613. this.materials[i].unfreeze();
  24614. }
  24615. };
  24616. Scene.prototype.dispose = function () {
  24617. this.beforeRender = null;
  24618. this.afterRender = null;
  24619. this.skeletons = [];
  24620. this.morphTargetManagers = [];
  24621. this.importedMeshesFiles = new Array();
  24622. this.stopAllAnimations();
  24623. this.resetCachedMaterial();
  24624. for (var key in this._depthRenderer) {
  24625. this._depthRenderer[key].dispose();
  24626. }
  24627. if (this._gamepadManager) {
  24628. this._gamepadManager.dispose();
  24629. this._gamepadManager = null;
  24630. }
  24631. // Smart arrays
  24632. if (this.activeCamera) {
  24633. this.activeCamera._activeMeshes.dispose();
  24634. this.activeCamera = null;
  24635. }
  24636. this._activeMeshes.dispose();
  24637. this._renderingManager.dispose();
  24638. this._processedMaterials.dispose();
  24639. this._activeParticleSystems.dispose();
  24640. this._activeSkeletons.dispose();
  24641. this._softwareSkinnedMeshes.dispose();
  24642. this._renderTargets.dispose();
  24643. if (this._boundingBoxRenderer) {
  24644. this._boundingBoxRenderer.dispose();
  24645. }
  24646. this._meshesForIntersections.dispose();
  24647. this._toBeDisposed.dispose();
  24648. // Abort active requests
  24649. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24650. var request = _a[_i];
  24651. request.abort();
  24652. }
  24653. // Debug layer
  24654. if (this._debugLayer) {
  24655. this._debugLayer.hide();
  24656. }
  24657. // Events
  24658. this.onDisposeObservable.notifyObservers(this);
  24659. this.onDisposeObservable.clear();
  24660. this.onBeforeRenderObservable.clear();
  24661. this.onAfterRenderObservable.clear();
  24662. this.OnBeforeRenderTargetsRenderObservable.clear();
  24663. this.OnAfterRenderTargetsRenderObservable.clear();
  24664. this.onAfterStepObservable.clear();
  24665. this.onBeforeStepObservable.clear();
  24666. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24667. this.onAfterActiveMeshesEvaluationObservable.clear();
  24668. this.onBeforeParticlesRenderingObservable.clear();
  24669. this.onAfterParticlesRenderingObservable.clear();
  24670. this.onBeforeSpritesRenderingObservable.clear();
  24671. this.onAfterSpritesRenderingObservable.clear();
  24672. this.onBeforeDrawPhaseObservable.clear();
  24673. this.onAfterDrawPhaseObservable.clear();
  24674. this.onBeforePhysicsObservable.clear();
  24675. this.onAfterPhysicsObservable.clear();
  24676. this.onBeforeAnimationsObservable.clear();
  24677. this.onAfterAnimationsObservable.clear();
  24678. this.onDataLoadedObservable.clear();
  24679. this.detachControl();
  24680. // Release sounds & sounds tracks
  24681. if (BABYLON.AudioEngine) {
  24682. this.disposeSounds();
  24683. }
  24684. // VR Helper
  24685. if (this.VRHelper) {
  24686. this.VRHelper.dispose();
  24687. }
  24688. // Detach cameras
  24689. var canvas = this._engine.getRenderingCanvas();
  24690. if (canvas) {
  24691. var index;
  24692. for (index = 0; index < this.cameras.length; index++) {
  24693. this.cameras[index].detachControl(canvas);
  24694. }
  24695. }
  24696. // Release animation groups
  24697. while (this.animationGroups.length) {
  24698. this.animationGroups[0].dispose();
  24699. }
  24700. // Release lights
  24701. while (this.lights.length) {
  24702. this.lights[0].dispose();
  24703. }
  24704. // Release meshes
  24705. while (this.meshes.length) {
  24706. this.meshes[0].dispose(true);
  24707. }
  24708. while (this.transformNodes.length) {
  24709. this.removeTransformNode(this.transformNodes[0]);
  24710. }
  24711. // Release cameras
  24712. while (this.cameras.length) {
  24713. this.cameras[0].dispose();
  24714. }
  24715. // Release materials
  24716. if (this.defaultMaterial) {
  24717. this.defaultMaterial.dispose();
  24718. }
  24719. while (this.multiMaterials.length) {
  24720. this.multiMaterials[0].dispose();
  24721. }
  24722. while (this.materials.length) {
  24723. this.materials[0].dispose();
  24724. }
  24725. // Release particles
  24726. while (this.particleSystems.length) {
  24727. this.particleSystems[0].dispose();
  24728. }
  24729. // Release sprites
  24730. while (this.spriteManagers.length) {
  24731. this.spriteManagers[0].dispose();
  24732. }
  24733. // Release postProcesses
  24734. while (this.postProcesses.length) {
  24735. this.postProcesses[0].dispose();
  24736. }
  24737. // Release layers
  24738. while (this.layers.length) {
  24739. this.layers[0].dispose();
  24740. }
  24741. while (this.effectLayers.length) {
  24742. this.effectLayers[0].dispose();
  24743. }
  24744. // Release textures
  24745. while (this.textures.length) {
  24746. this.textures[0].dispose();
  24747. }
  24748. // Release UBO
  24749. this._sceneUbo.dispose();
  24750. if (this._alternateSceneUbo) {
  24751. this._alternateSceneUbo.dispose();
  24752. }
  24753. // Post-processes
  24754. this.postProcessManager.dispose();
  24755. if (this._postProcessRenderPipelineManager) {
  24756. this._postProcessRenderPipelineManager.dispose();
  24757. }
  24758. // Physics
  24759. if (this._physicsEngine) {
  24760. this.disablePhysicsEngine();
  24761. }
  24762. // Remove from engine
  24763. index = this._engine.scenes.indexOf(this);
  24764. if (index > -1) {
  24765. this._engine.scenes.splice(index, 1);
  24766. }
  24767. this._engine.wipeCaches(true);
  24768. this._isDisposed = true;
  24769. };
  24770. Object.defineProperty(Scene.prototype, "isDisposed", {
  24771. get: function () {
  24772. return this._isDisposed;
  24773. },
  24774. enumerable: true,
  24775. configurable: true
  24776. });
  24777. // Release sounds & sounds tracks
  24778. Scene.prototype.disposeSounds = function () {
  24779. if (!this._mainSoundTrack) {
  24780. return;
  24781. }
  24782. this.mainSoundTrack.dispose();
  24783. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24784. this.soundTracks[scIndex].dispose();
  24785. }
  24786. };
  24787. // Octrees
  24788. /**
  24789. * Get the world extend vectors with an optional filter
  24790. *
  24791. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24792. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24793. */
  24794. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24795. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24796. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24797. filterPredicate = filterPredicate || (function () { return true; });
  24798. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24799. mesh.computeWorldMatrix(true);
  24800. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24801. return;
  24802. }
  24803. var boundingInfo = mesh.getBoundingInfo();
  24804. var minBox = boundingInfo.boundingBox.minimumWorld;
  24805. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24806. BABYLON.Tools.CheckExtends(minBox, min, max);
  24807. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24808. });
  24809. return {
  24810. min: min,
  24811. max: max
  24812. };
  24813. };
  24814. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24815. if (maxCapacity === void 0) { maxCapacity = 64; }
  24816. if (maxDepth === void 0) { maxDepth = 2; }
  24817. if (!this._selectionOctree) {
  24818. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24819. }
  24820. var worldExtends = this.getWorldExtends();
  24821. // Update octree
  24822. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24823. return this._selectionOctree;
  24824. };
  24825. // Picking
  24826. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24827. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24828. var result = BABYLON.Ray.Zero();
  24829. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24830. return result;
  24831. };
  24832. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24833. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24834. var engine = this._engine;
  24835. if (!camera) {
  24836. if (!this.activeCamera)
  24837. throw new Error("Active camera not set");
  24838. camera = this.activeCamera;
  24839. }
  24840. var cameraViewport = camera.viewport;
  24841. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24842. // Moving coordinates to local viewport world
  24843. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24844. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24845. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24846. return this;
  24847. };
  24848. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24849. var result = BABYLON.Ray.Zero();
  24850. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24851. return result;
  24852. };
  24853. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24854. if (!BABYLON.PickingInfo) {
  24855. return this;
  24856. }
  24857. var engine = this._engine;
  24858. if (!camera) {
  24859. if (!this.activeCamera)
  24860. throw new Error("Active camera not set");
  24861. camera = this.activeCamera;
  24862. }
  24863. var cameraViewport = camera.viewport;
  24864. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24865. var identity = BABYLON.Matrix.Identity();
  24866. // Moving coordinates to local viewport world
  24867. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24868. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24869. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24870. return this;
  24871. };
  24872. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24873. if (!BABYLON.PickingInfo) {
  24874. return null;
  24875. }
  24876. var pickingInfo = null;
  24877. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24878. var mesh = this.meshes[meshIndex];
  24879. if (predicate) {
  24880. if (!predicate(mesh)) {
  24881. continue;
  24882. }
  24883. }
  24884. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24885. continue;
  24886. }
  24887. var world = mesh.getWorldMatrix();
  24888. var ray = rayFunction(world);
  24889. var result = mesh.intersects(ray, fastCheck);
  24890. if (!result || !result.hit)
  24891. continue;
  24892. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24893. continue;
  24894. pickingInfo = result;
  24895. if (fastCheck) {
  24896. break;
  24897. }
  24898. }
  24899. return pickingInfo || new BABYLON.PickingInfo();
  24900. };
  24901. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24902. if (!BABYLON.PickingInfo) {
  24903. return null;
  24904. }
  24905. var pickingInfos = new Array();
  24906. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24907. var mesh = this.meshes[meshIndex];
  24908. if (predicate) {
  24909. if (!predicate(mesh)) {
  24910. continue;
  24911. }
  24912. }
  24913. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24914. continue;
  24915. }
  24916. var world = mesh.getWorldMatrix();
  24917. var ray = rayFunction(world);
  24918. var result = mesh.intersects(ray, false);
  24919. if (!result || !result.hit)
  24920. continue;
  24921. pickingInfos.push(result);
  24922. }
  24923. return pickingInfos;
  24924. };
  24925. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24926. if (!BABYLON.PickingInfo) {
  24927. return null;
  24928. }
  24929. var pickingInfo = null;
  24930. if (!camera) {
  24931. if (!this.activeCamera) {
  24932. return null;
  24933. }
  24934. camera = this.activeCamera;
  24935. }
  24936. if (this.spriteManagers.length > 0) {
  24937. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24938. var spriteManager = this.spriteManagers[spriteIndex];
  24939. if (!spriteManager.isPickable) {
  24940. continue;
  24941. }
  24942. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24943. if (!result || !result.hit)
  24944. continue;
  24945. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24946. continue;
  24947. pickingInfo = result;
  24948. if (fastCheck) {
  24949. break;
  24950. }
  24951. }
  24952. }
  24953. return pickingInfo || new BABYLON.PickingInfo();
  24954. };
  24955. /** Launch a ray to try to pick a mesh in the scene
  24956. * @param x position on screen
  24957. * @param y position on screen
  24958. * @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
  24959. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24960. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24961. */
  24962. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24963. var _this = this;
  24964. if (!BABYLON.PickingInfo) {
  24965. return null;
  24966. }
  24967. return this._internalPick(function (world) {
  24968. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24969. return _this._tempPickingRay;
  24970. }, predicate, fastCheck);
  24971. };
  24972. /** Launch a ray to try to pick a sprite in the scene
  24973. * @param x position on screen
  24974. * @param y position on screen
  24975. * @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
  24976. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24977. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24978. */
  24979. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24980. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24981. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24982. };
  24983. /** Use the given ray to pick a mesh in the scene
  24984. * @param ray The ray to use to pick meshes
  24985. * @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
  24986. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24987. */
  24988. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24989. var _this = this;
  24990. return this._internalPick(function (world) {
  24991. if (!_this._pickWithRayInverseMatrix) {
  24992. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24993. }
  24994. world.invertToRef(_this._pickWithRayInverseMatrix);
  24995. if (!_this._cachedRayForTransform) {
  24996. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24997. }
  24998. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24999. return _this._cachedRayForTransform;
  25000. }, predicate, fastCheck);
  25001. };
  25002. /**
  25003. * Launch a ray to try to pick a mesh in the scene
  25004. * @param x X position on screen
  25005. * @param y Y position on screen
  25006. * @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
  25007. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25008. */
  25009. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25010. var _this = this;
  25011. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25012. };
  25013. /**
  25014. * Launch a ray to try to pick a mesh in the scene
  25015. * @param ray Ray to use
  25016. * @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
  25017. */
  25018. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25019. var _this = this;
  25020. return this._internalMultiPick(function (world) {
  25021. if (!_this._pickWithRayInverseMatrix) {
  25022. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25023. }
  25024. world.invertToRef(_this._pickWithRayInverseMatrix);
  25025. if (!_this._cachedRayForTransform) {
  25026. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25027. }
  25028. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25029. return _this._cachedRayForTransform;
  25030. }, predicate);
  25031. };
  25032. Scene.prototype.setPointerOverMesh = function (mesh) {
  25033. if (this._pointerOverMesh === mesh) {
  25034. return;
  25035. }
  25036. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25037. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25038. }
  25039. this._pointerOverMesh = mesh;
  25040. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25041. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25042. }
  25043. };
  25044. Scene.prototype.getPointerOverMesh = function () {
  25045. return this._pointerOverMesh;
  25046. };
  25047. Scene.prototype.setPointerOverSprite = function (sprite) {
  25048. if (this._pointerOverSprite === sprite) {
  25049. return;
  25050. }
  25051. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25052. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25053. }
  25054. this._pointerOverSprite = sprite;
  25055. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25056. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25057. }
  25058. };
  25059. Scene.prototype.getPointerOverSprite = function () {
  25060. return this._pointerOverSprite;
  25061. };
  25062. // Physics
  25063. Scene.prototype.getPhysicsEngine = function () {
  25064. return this._physicsEngine;
  25065. };
  25066. /**
  25067. * Enables physics to the current scene
  25068. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25069. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25070. * @return {boolean} was the physics engine initialized
  25071. */
  25072. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25073. if (gravity === void 0) { gravity = null; }
  25074. if (this._physicsEngine) {
  25075. return true;
  25076. }
  25077. try {
  25078. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25079. return true;
  25080. }
  25081. catch (e) {
  25082. BABYLON.Tools.Error(e.message);
  25083. return false;
  25084. }
  25085. };
  25086. Scene.prototype.disablePhysicsEngine = function () {
  25087. if (!this._physicsEngine) {
  25088. return;
  25089. }
  25090. this._physicsEngine.dispose();
  25091. this._physicsEngine = null;
  25092. };
  25093. Scene.prototype.isPhysicsEnabled = function () {
  25094. return this._physicsEngine !== undefined;
  25095. };
  25096. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25097. var mesh = compound.parts[0].mesh;
  25098. if (mesh.physicsImpostor) {
  25099. mesh.physicsImpostor.dispose();
  25100. mesh.physicsImpostor = null;
  25101. }
  25102. };
  25103. // Misc.
  25104. Scene.prototype._rebuildGeometries = function () {
  25105. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25106. var geometry = _a[_i];
  25107. geometry._rebuild();
  25108. }
  25109. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25110. var mesh = _c[_b];
  25111. mesh._rebuild();
  25112. }
  25113. if (this.postProcessManager) {
  25114. this.postProcessManager._rebuild();
  25115. }
  25116. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25117. var layer = _e[_d];
  25118. layer._rebuild();
  25119. }
  25120. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25121. var effectLayer = _g[_f];
  25122. effectLayer._rebuild();
  25123. }
  25124. if (this._boundingBoxRenderer) {
  25125. this._boundingBoxRenderer._rebuild();
  25126. }
  25127. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25128. var system = _j[_h];
  25129. system.rebuild();
  25130. }
  25131. if (this._postProcessRenderPipelineManager) {
  25132. this._postProcessRenderPipelineManager._rebuild();
  25133. }
  25134. };
  25135. Scene.prototype._rebuildTextures = function () {
  25136. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25137. var texture = _a[_i];
  25138. texture._rebuild();
  25139. }
  25140. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25141. };
  25142. /**
  25143. * Creates a default light for the scene.
  25144. * @param replace Whether to replace the existing lights in the scene.
  25145. */
  25146. Scene.prototype.createDefaultLight = function (replace) {
  25147. if (replace === void 0) { replace = false; }
  25148. // Dispose existing light in replace mode.
  25149. if (replace) {
  25150. if (this.lights) {
  25151. for (var i = 0; i < this.lights.length; i++) {
  25152. this.lights[i].dispose();
  25153. }
  25154. }
  25155. }
  25156. // Light
  25157. if (this.lights.length === 0) {
  25158. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25159. }
  25160. };
  25161. /**
  25162. * Creates a default camera for the scene.
  25163. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25164. * @param replace Whether to replace the existing active camera in the scene.
  25165. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25166. */
  25167. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25168. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25169. if (replace === void 0) { replace = false; }
  25170. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25171. // Dispose existing camera in replace mode.
  25172. if (replace) {
  25173. if (this.activeCamera) {
  25174. this.activeCamera.dispose();
  25175. this.activeCamera = null;
  25176. }
  25177. }
  25178. // Camera
  25179. if (!this.activeCamera) {
  25180. var worldExtends = this.getWorldExtends();
  25181. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25182. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25183. var camera;
  25184. var radius = worldSize.length() * 1.5;
  25185. // empty scene scenario!
  25186. if (!isFinite(radius)) {
  25187. radius = 1;
  25188. worldCenter.copyFromFloats(0, 0, 0);
  25189. }
  25190. if (createArcRotateCamera) {
  25191. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25192. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25193. arcRotateCamera.wheelPrecision = 100 / radius;
  25194. camera = arcRotateCamera;
  25195. }
  25196. else {
  25197. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25198. freeCamera.setTarget(worldCenter);
  25199. camera = freeCamera;
  25200. }
  25201. camera.minZ = radius * 0.01;
  25202. camera.maxZ = radius * 1000;
  25203. camera.speed = radius * 0.2;
  25204. this.activeCamera = camera;
  25205. var canvas = this.getEngine().getRenderingCanvas();
  25206. if (attachCameraControls && canvas) {
  25207. camera.attachControl(canvas);
  25208. }
  25209. }
  25210. };
  25211. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25212. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25213. if (replace === void 0) { replace = false; }
  25214. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25215. this.createDefaultLight(replace);
  25216. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25217. };
  25218. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25219. if (pbr === void 0) { pbr = false; }
  25220. if (scale === void 0) { scale = 1000; }
  25221. if (blur === void 0) { blur = 0; }
  25222. if (environmentTexture) {
  25223. this.environmentTexture = environmentTexture;
  25224. }
  25225. if (!this.environmentTexture) {
  25226. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25227. return null;
  25228. }
  25229. // Skybox
  25230. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25231. if (pbr) {
  25232. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25233. hdrSkyboxMaterial.backFaceCulling = false;
  25234. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25235. if (hdrSkyboxMaterial.reflectionTexture) {
  25236. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25237. }
  25238. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25239. hdrSkyboxMaterial.disableLighting = true;
  25240. hdrSkyboxMaterial.twoSidedLighting = true;
  25241. hdrSkybox.infiniteDistance = true;
  25242. hdrSkybox.material = hdrSkyboxMaterial;
  25243. }
  25244. else {
  25245. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25246. skyboxMaterial.backFaceCulling = false;
  25247. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25248. if (skyboxMaterial.reflectionTexture) {
  25249. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25250. }
  25251. skyboxMaterial.disableLighting = true;
  25252. hdrSkybox.infiniteDistance = true;
  25253. hdrSkybox.material = skyboxMaterial;
  25254. }
  25255. return hdrSkybox;
  25256. };
  25257. Scene.prototype.createDefaultEnvironment = function (options) {
  25258. if (BABYLON.EnvironmentHelper) {
  25259. return new BABYLON.EnvironmentHelper(options, this);
  25260. }
  25261. return null;
  25262. };
  25263. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25264. if (webVROptions === void 0) { webVROptions = {}; }
  25265. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25266. };
  25267. // Tags
  25268. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25269. if (tagsQuery === undefined) {
  25270. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25271. return list;
  25272. }
  25273. var listByTags = [];
  25274. forEach = forEach || (function (item) { return; });
  25275. for (var i in list) {
  25276. var item = list[i];
  25277. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25278. listByTags.push(item);
  25279. forEach(item);
  25280. }
  25281. }
  25282. return listByTags;
  25283. };
  25284. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25285. return this._getByTags(this.meshes, tagsQuery, forEach);
  25286. };
  25287. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25288. return this._getByTags(this.cameras, tagsQuery, forEach);
  25289. };
  25290. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25291. return this._getByTags(this.lights, tagsQuery, forEach);
  25292. };
  25293. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25294. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25295. };
  25296. /**
  25297. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25298. * This allowed control for front to back rendering or reversly depending of the special needs.
  25299. *
  25300. * @param renderingGroupId The rendering group id corresponding to its index
  25301. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25302. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25303. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25304. */
  25305. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25306. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25307. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25308. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25309. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25310. };
  25311. /**
  25312. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25313. *
  25314. * @param renderingGroupId The rendering group id corresponding to its index
  25315. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25316. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25317. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25318. */
  25319. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25320. if (depth === void 0) { depth = true; }
  25321. if (stencil === void 0) { stencil = true; }
  25322. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25323. };
  25324. /**
  25325. * Will flag all materials as dirty to trigger new shader compilation
  25326. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25327. */
  25328. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25329. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25330. var material = _a[_i];
  25331. if (predicate && !predicate(material)) {
  25332. continue;
  25333. }
  25334. material.markAsDirty(flag);
  25335. }
  25336. };
  25337. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25338. var _this = this;
  25339. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25340. this._activeRequests.push(request);
  25341. request.onCompleteObservable.add(function (request) {
  25342. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25343. });
  25344. return request;
  25345. };
  25346. /** @ignore */
  25347. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25348. var _this = this;
  25349. return new Promise(function (resolve, reject) {
  25350. _this._loadFile(url, function (data) {
  25351. resolve(data);
  25352. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25353. reject(exception);
  25354. });
  25355. });
  25356. };
  25357. // Statics
  25358. Scene._FOGMODE_NONE = 0;
  25359. Scene._FOGMODE_EXP = 1;
  25360. Scene._FOGMODE_EXP2 = 2;
  25361. Scene._FOGMODE_LINEAR = 3;
  25362. Scene._uniqueIdCounter = 0;
  25363. Scene.MinDeltaTime = 1.0;
  25364. Scene.MaxDeltaTime = 1000.0;
  25365. /** The distance in pixel that you have to move to prevent some events */
  25366. Scene.DragMovementThreshold = 10; // in pixels
  25367. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25368. Scene.LongPressDelay = 500; // in milliseconds
  25369. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25370. Scene.DoubleClickDelay = 300; // in milliseconds
  25371. /** If you need to check double click without raising a single click at first click, enable this flag */
  25372. Scene.ExclusiveDoubleClickMode = false;
  25373. return Scene;
  25374. }());
  25375. BABYLON.Scene = Scene;
  25376. })(BABYLON || (BABYLON = {}));
  25377. //# sourceMappingURL=babylon.scene.js.map
  25378. var BABYLON;
  25379. (function (BABYLON) {
  25380. /**
  25381. * Set of assets to keep when moving a scene into an asset container.
  25382. */
  25383. var KeepAssets = /** @class */ (function () {
  25384. function KeepAssets() {
  25385. /**
  25386. * Cameras to keep.
  25387. */
  25388. this.cameras = new Array();
  25389. /**
  25390. * Lights to keep.
  25391. */
  25392. this.lights = new Array();
  25393. /**
  25394. * Meshes to keep.
  25395. */
  25396. this.meshes = new Array();
  25397. /**
  25398. * Skeletons to keep.
  25399. */
  25400. this.skeletons = new Array();
  25401. /**
  25402. * ParticleSystems to keep.
  25403. */
  25404. this.particleSystems = new Array();
  25405. /**
  25406. * Animations to keep.
  25407. */
  25408. this.animations = new Array();
  25409. /**
  25410. * MultiMaterials to keep.
  25411. */
  25412. this.multiMaterials = new Array();
  25413. /**
  25414. * Materials to keep.
  25415. */
  25416. this.materials = new Array();
  25417. /**
  25418. * MorphTargetManagers to keep.
  25419. */
  25420. this.morphTargetManagers = new Array();
  25421. /**
  25422. * Geometries to keep.
  25423. */
  25424. this.geometries = new Array();
  25425. /**
  25426. * TransformNodes to keep.
  25427. */
  25428. this.transformNodes = new Array();
  25429. /**
  25430. * LensFlareSystems to keep.
  25431. */
  25432. this.lensFlareSystems = new Array();
  25433. /**
  25434. * ShadowGenerators to keep.
  25435. */
  25436. this.shadowGenerators = new Array();
  25437. /**
  25438. * ActionManagers to keep.
  25439. */
  25440. this.actionManagers = new Array();
  25441. /**
  25442. * Sounds to keep.
  25443. */
  25444. this.sounds = new Array();
  25445. }
  25446. return KeepAssets;
  25447. }());
  25448. BABYLON.KeepAssets = KeepAssets;
  25449. /**
  25450. * Container with a set of assets that can be added or removed from a scene.
  25451. */
  25452. var AssetContainer = /** @class */ (function () {
  25453. /**
  25454. * Instantiates an AssetContainer.
  25455. * @param scene The scene the AssetContainer belongs to.
  25456. */
  25457. function AssetContainer(scene) {
  25458. // Objects
  25459. /**
  25460. * Cameras populated in the container.
  25461. */
  25462. this.cameras = new Array();
  25463. /**
  25464. * Lights populated in the container.
  25465. */
  25466. this.lights = new Array();
  25467. /**
  25468. * Meshes populated in the container.
  25469. */
  25470. this.meshes = new Array();
  25471. /**
  25472. * Skeletons populated in the container.
  25473. */
  25474. this.skeletons = new Array();
  25475. /**
  25476. * ParticleSystems populated in the container.
  25477. */
  25478. this.particleSystems = new Array();
  25479. /**
  25480. * Animations populated in the container.
  25481. */
  25482. this.animations = new Array();
  25483. /**
  25484. * MultiMaterials populated in the container.
  25485. */
  25486. this.multiMaterials = new Array();
  25487. /**
  25488. * Materials populated in the container.
  25489. */
  25490. this.materials = new Array();
  25491. /**
  25492. * MorphTargetManagers populated in the container.
  25493. */
  25494. this.morphTargetManagers = new Array();
  25495. /**
  25496. * Geometries populated in the container.
  25497. */
  25498. this.geometries = new Array();
  25499. /**
  25500. * TransformNodes populated in the container.
  25501. */
  25502. this.transformNodes = new Array();
  25503. /**
  25504. * LensFlareSystems populated in the container.
  25505. */
  25506. this.lensFlareSystems = new Array();
  25507. /**
  25508. * ShadowGenerators populated in the container.
  25509. */
  25510. this.shadowGenerators = new Array();
  25511. /**
  25512. * ActionManagers populated in the container.
  25513. */
  25514. this.actionManagers = new Array();
  25515. /**
  25516. * Sounds populated in the container.
  25517. */
  25518. this.sounds = new Array();
  25519. this.scene = scene;
  25520. }
  25521. /**
  25522. * Adds all the assets from the container to the scene.
  25523. */
  25524. AssetContainer.prototype.addAllToScene = function () {
  25525. var _this = this;
  25526. this.cameras.forEach(function (o) {
  25527. _this.scene.addCamera(o);
  25528. });
  25529. this.lights.forEach(function (o) {
  25530. _this.scene.addLight(o);
  25531. });
  25532. this.meshes.forEach(function (o) {
  25533. _this.scene.addMesh(o);
  25534. });
  25535. this.skeletons.forEach(function (o) {
  25536. _this.scene.addSkeleton(o);
  25537. });
  25538. this.particleSystems.forEach(function (o) {
  25539. _this.scene.addParticleSystem(o);
  25540. });
  25541. this.animations.forEach(function (o) {
  25542. _this.scene.addAnimation(o);
  25543. });
  25544. this.multiMaterials.forEach(function (o) {
  25545. _this.scene.addMultiMaterial(o);
  25546. });
  25547. this.materials.forEach(function (o) {
  25548. _this.scene.addMaterial(o);
  25549. });
  25550. this.morphTargetManagers.forEach(function (o) {
  25551. _this.scene.addMorphTargetManager(o);
  25552. });
  25553. this.geometries.forEach(function (o) {
  25554. _this.scene.addGeometry(o);
  25555. });
  25556. this.transformNodes.forEach(function (o) {
  25557. _this.scene.addTransformNode(o);
  25558. });
  25559. this.lensFlareSystems.forEach(function (o) {
  25560. _this.scene.addLensFlareSystem(o);
  25561. });
  25562. this.actionManagers.forEach(function (o) {
  25563. _this.scene.addActionManager(o);
  25564. });
  25565. this.sounds.forEach(function (o) {
  25566. o.play();
  25567. o.autoplay = true;
  25568. _this.scene.mainSoundTrack.AddSound(o);
  25569. });
  25570. };
  25571. /**
  25572. * Removes all the assets in the container from the scene
  25573. */
  25574. AssetContainer.prototype.removeAllFromScene = function () {
  25575. var _this = this;
  25576. this.cameras.forEach(function (o) {
  25577. _this.scene.removeCamera(o);
  25578. });
  25579. this.lights.forEach(function (o) {
  25580. _this.scene.removeLight(o);
  25581. });
  25582. this.meshes.forEach(function (o) {
  25583. _this.scene.removeMesh(o);
  25584. });
  25585. this.skeletons.forEach(function (o) {
  25586. _this.scene.removeSkeleton(o);
  25587. });
  25588. this.particleSystems.forEach(function (o) {
  25589. _this.scene.removeParticleSystem(o);
  25590. });
  25591. this.animations.forEach(function (o) {
  25592. _this.scene.removeAnimation(o);
  25593. });
  25594. this.multiMaterials.forEach(function (o) {
  25595. _this.scene.removeMultiMaterial(o);
  25596. });
  25597. this.materials.forEach(function (o) {
  25598. _this.scene.removeMaterial(o);
  25599. });
  25600. this.morphTargetManagers.forEach(function (o) {
  25601. _this.scene.removeMorphTargetManager(o);
  25602. });
  25603. this.geometries.forEach(function (o) {
  25604. _this.scene.removeGeometry(o);
  25605. });
  25606. this.transformNodes.forEach(function (o) {
  25607. _this.scene.removeTransformNode(o);
  25608. });
  25609. this.lensFlareSystems.forEach(function (o) {
  25610. _this.scene.removeLensFlareSystem(o);
  25611. });
  25612. this.actionManagers.forEach(function (o) {
  25613. _this.scene.removeActionManager(o);
  25614. });
  25615. this.sounds.forEach(function (o) {
  25616. o.stop();
  25617. o.autoplay = false;
  25618. _this.scene.mainSoundTrack.RemoveSound(o);
  25619. });
  25620. };
  25621. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25622. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25623. var asset = sourceAssets_1[_i];
  25624. var move = true;
  25625. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25626. var keepAsset = keepAssets_1[_a];
  25627. if (asset === keepAsset) {
  25628. move = false;
  25629. break;
  25630. }
  25631. }
  25632. if (move) {
  25633. targetAssets.push(asset);
  25634. }
  25635. }
  25636. };
  25637. /**
  25638. * Removes all the assets contained in the scene and adds them to the container.
  25639. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25640. */
  25641. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25642. if (keepAssets === undefined) {
  25643. keepAssets = new KeepAssets();
  25644. }
  25645. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25646. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25647. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25648. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25649. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25650. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25651. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25652. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25653. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25654. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25655. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25656. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25657. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25658. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25659. this.removeAllFromScene();
  25660. };
  25661. return AssetContainer;
  25662. }());
  25663. BABYLON.AssetContainer = AssetContainer;
  25664. })(BABYLON || (BABYLON = {}));
  25665. //# sourceMappingURL=babylon.assetContainer.js.map
  25666. var BABYLON;
  25667. (function (BABYLON) {
  25668. var Buffer = /** @class */ (function () {
  25669. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25670. if (instanced === void 0) { instanced = false; }
  25671. if (engine instanceof BABYLON.Mesh) {
  25672. this._engine = engine.getScene().getEngine();
  25673. }
  25674. else {
  25675. this._engine = engine;
  25676. }
  25677. this._updatable = updatable;
  25678. this._instanced = instanced;
  25679. this._data = data;
  25680. this._strideSize = stride;
  25681. if (!postponeInternalCreation) {
  25682. this.create();
  25683. }
  25684. }
  25685. /**
  25686. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25687. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25688. * @param offset defines offset in the buffer (0 by default)
  25689. * @param size defines the size in floats of attributes (position is 3 for instance)
  25690. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25691. * @param instanced defines if the vertex buffer contains indexed data
  25692. * @returns the new vertex buffer
  25693. */
  25694. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25695. // a lot of these parameters are ignored as they are overriden by the buffer
  25696. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25697. };
  25698. // Properties
  25699. Buffer.prototype.isUpdatable = function () {
  25700. return this._updatable;
  25701. };
  25702. Buffer.prototype.getData = function () {
  25703. return this._data;
  25704. };
  25705. Buffer.prototype.getBuffer = function () {
  25706. return this._buffer;
  25707. };
  25708. Buffer.prototype.getStrideSize = function () {
  25709. return this._strideSize;
  25710. };
  25711. // public getIsInstanced(): boolean {
  25712. // return this._instanced;
  25713. // }
  25714. // public get instanceDivisor(): number {
  25715. // return this._instanceDivisor;
  25716. // }
  25717. // public set instanceDivisor(value: number) {
  25718. // this._instanceDivisor = value;
  25719. // if (value == 0) {
  25720. // this._instanced = false;
  25721. // } else {
  25722. // this._instanced = true;
  25723. // }
  25724. // }
  25725. // Methods
  25726. Buffer.prototype.create = function (data) {
  25727. if (data === void 0) { data = null; }
  25728. if (!data && this._buffer) {
  25729. return; // nothing to do
  25730. }
  25731. data = data || this._data;
  25732. if (!data) {
  25733. return;
  25734. }
  25735. if (!this._buffer) {
  25736. if (this._updatable) {
  25737. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25738. this._data = data;
  25739. }
  25740. else {
  25741. this._buffer = this._engine.createVertexBuffer(data);
  25742. }
  25743. }
  25744. else if (this._updatable) {
  25745. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25746. this._data = data;
  25747. }
  25748. };
  25749. Buffer.prototype._rebuild = function () {
  25750. this._buffer = null;
  25751. this.create(this._data);
  25752. };
  25753. Buffer.prototype.update = function (data) {
  25754. this.create(data);
  25755. };
  25756. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25757. if (!this._buffer) {
  25758. return;
  25759. }
  25760. if (this._updatable) {
  25761. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25762. this._data = null;
  25763. }
  25764. };
  25765. Buffer.prototype.dispose = function () {
  25766. if (!this._buffer) {
  25767. return;
  25768. }
  25769. if (this._engine._releaseBuffer(this._buffer)) {
  25770. this._buffer = null;
  25771. }
  25772. };
  25773. return Buffer;
  25774. }());
  25775. BABYLON.Buffer = Buffer;
  25776. })(BABYLON || (BABYLON = {}));
  25777. //# sourceMappingURL=babylon.buffer.js.map
  25778. var BABYLON;
  25779. (function (BABYLON) {
  25780. var VertexBuffer = /** @class */ (function () {
  25781. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25782. if (data instanceof BABYLON.Buffer) {
  25783. if (!stride) {
  25784. stride = data.getStrideSize();
  25785. }
  25786. this._buffer = data;
  25787. this._ownsBuffer = false;
  25788. }
  25789. else {
  25790. if (!stride) {
  25791. stride = VertexBuffer.DeduceStride(kind);
  25792. }
  25793. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25794. this._ownsBuffer = true;
  25795. }
  25796. this._stride = stride;
  25797. this._instanced = instanced !== undefined ? instanced : false;
  25798. this._instanceDivisor = instanced ? 1 : 0;
  25799. this._offset = offset ? offset : 0;
  25800. this._size = size ? size : stride;
  25801. this._kind = kind;
  25802. }
  25803. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25804. /**
  25805. * Gets or sets the instance divisor when in instanced mode
  25806. */
  25807. get: function () {
  25808. return this._instanceDivisor;
  25809. },
  25810. set: function (value) {
  25811. this._instanceDivisor = value;
  25812. if (value == 0) {
  25813. this._instanced = false;
  25814. }
  25815. else {
  25816. this._instanced = true;
  25817. }
  25818. },
  25819. enumerable: true,
  25820. configurable: true
  25821. });
  25822. VertexBuffer.prototype._rebuild = function () {
  25823. if (!this._buffer) {
  25824. return;
  25825. }
  25826. this._buffer._rebuild();
  25827. };
  25828. /**
  25829. * Returns the kind of the VertexBuffer (string).
  25830. */
  25831. VertexBuffer.prototype.getKind = function () {
  25832. return this._kind;
  25833. };
  25834. // Properties
  25835. /**
  25836. * Boolean : is the VertexBuffer updatable ?
  25837. */
  25838. VertexBuffer.prototype.isUpdatable = function () {
  25839. return this._buffer.isUpdatable();
  25840. };
  25841. /**
  25842. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25843. */
  25844. VertexBuffer.prototype.getData = function () {
  25845. return this._buffer.getData();
  25846. };
  25847. /**
  25848. * Returns the WebGLBuffer associated to the VertexBuffer.
  25849. */
  25850. VertexBuffer.prototype.getBuffer = function () {
  25851. return this._buffer.getBuffer();
  25852. };
  25853. /**
  25854. * Returns the stride of the VertexBuffer (integer).
  25855. */
  25856. VertexBuffer.prototype.getStrideSize = function () {
  25857. return this._stride;
  25858. };
  25859. /**
  25860. * Returns the offset (integer).
  25861. */
  25862. VertexBuffer.prototype.getOffset = function () {
  25863. return this._offset;
  25864. };
  25865. /**
  25866. * Returns the VertexBuffer total size (integer).
  25867. */
  25868. VertexBuffer.prototype.getSize = function () {
  25869. return this._size;
  25870. };
  25871. /**
  25872. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25873. */
  25874. VertexBuffer.prototype.getIsInstanced = function () {
  25875. return this._instanced;
  25876. };
  25877. /**
  25878. * Returns the instancing divisor, zero for non-instanced (integer).
  25879. */
  25880. VertexBuffer.prototype.getInstanceDivisor = function () {
  25881. return this._instanceDivisor;
  25882. };
  25883. // Methods
  25884. /**
  25885. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25886. * Returns the created WebGLBuffer.
  25887. */
  25888. VertexBuffer.prototype.create = function (data) {
  25889. return this._buffer.create(data);
  25890. };
  25891. /**
  25892. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25893. * This function will create a new buffer if the current one is not updatable
  25894. * Returns the updated WebGLBuffer.
  25895. */
  25896. VertexBuffer.prototype.update = function (data) {
  25897. return this._buffer.update(data);
  25898. };
  25899. /**
  25900. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25901. * Returns the directly updated WebGLBuffer.
  25902. */
  25903. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25904. return this._buffer.updateDirectly(data, offset);
  25905. };
  25906. /**
  25907. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25908. */
  25909. VertexBuffer.prototype.dispose = function () {
  25910. if (this._ownsBuffer) {
  25911. this._buffer.dispose();
  25912. }
  25913. };
  25914. Object.defineProperty(VertexBuffer, "PositionKind", {
  25915. get: function () {
  25916. return VertexBuffer._PositionKind;
  25917. },
  25918. enumerable: true,
  25919. configurable: true
  25920. });
  25921. Object.defineProperty(VertexBuffer, "NormalKind", {
  25922. get: function () {
  25923. return VertexBuffer._NormalKind;
  25924. },
  25925. enumerable: true,
  25926. configurable: true
  25927. });
  25928. Object.defineProperty(VertexBuffer, "TangentKind", {
  25929. get: function () {
  25930. return VertexBuffer._TangentKind;
  25931. },
  25932. enumerable: true,
  25933. configurable: true
  25934. });
  25935. Object.defineProperty(VertexBuffer, "UVKind", {
  25936. get: function () {
  25937. return VertexBuffer._UVKind;
  25938. },
  25939. enumerable: true,
  25940. configurable: true
  25941. });
  25942. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25943. get: function () {
  25944. return VertexBuffer._UV2Kind;
  25945. },
  25946. enumerable: true,
  25947. configurable: true
  25948. });
  25949. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25950. get: function () {
  25951. return VertexBuffer._UV3Kind;
  25952. },
  25953. enumerable: true,
  25954. configurable: true
  25955. });
  25956. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25957. get: function () {
  25958. return VertexBuffer._UV4Kind;
  25959. },
  25960. enumerable: true,
  25961. configurable: true
  25962. });
  25963. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25964. get: function () {
  25965. return VertexBuffer._UV5Kind;
  25966. },
  25967. enumerable: true,
  25968. configurable: true
  25969. });
  25970. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25971. get: function () {
  25972. return VertexBuffer._UV6Kind;
  25973. },
  25974. enumerable: true,
  25975. configurable: true
  25976. });
  25977. Object.defineProperty(VertexBuffer, "ColorKind", {
  25978. get: function () {
  25979. return VertexBuffer._ColorKind;
  25980. },
  25981. enumerable: true,
  25982. configurable: true
  25983. });
  25984. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25985. get: function () {
  25986. return VertexBuffer._MatricesIndicesKind;
  25987. },
  25988. enumerable: true,
  25989. configurable: true
  25990. });
  25991. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25992. get: function () {
  25993. return VertexBuffer._MatricesWeightsKind;
  25994. },
  25995. enumerable: true,
  25996. configurable: true
  25997. });
  25998. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25999. get: function () {
  26000. return VertexBuffer._MatricesIndicesExtraKind;
  26001. },
  26002. enumerable: true,
  26003. configurable: true
  26004. });
  26005. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26006. get: function () {
  26007. return VertexBuffer._MatricesWeightsExtraKind;
  26008. },
  26009. enumerable: true,
  26010. configurable: true
  26011. });
  26012. /**
  26013. * Deduces the stride given a kind.
  26014. * @param kind The kind string to deduce
  26015. * @returns The deduced stride
  26016. */
  26017. VertexBuffer.DeduceStride = function (kind) {
  26018. switch (kind) {
  26019. case VertexBuffer.UVKind:
  26020. case VertexBuffer.UV2Kind:
  26021. case VertexBuffer.UV3Kind:
  26022. case VertexBuffer.UV4Kind:
  26023. case VertexBuffer.UV5Kind:
  26024. case VertexBuffer.UV6Kind:
  26025. return 2;
  26026. case VertexBuffer.NormalKind:
  26027. case VertexBuffer.PositionKind:
  26028. return 3;
  26029. case VertexBuffer.ColorKind:
  26030. case VertexBuffer.MatricesIndicesKind:
  26031. case VertexBuffer.MatricesIndicesExtraKind:
  26032. case VertexBuffer.MatricesWeightsKind:
  26033. case VertexBuffer.MatricesWeightsExtraKind:
  26034. case VertexBuffer.TangentKind:
  26035. return 4;
  26036. default:
  26037. throw new Error("Invalid kind '" + kind + "'");
  26038. }
  26039. };
  26040. // Enums
  26041. VertexBuffer._PositionKind = "position";
  26042. VertexBuffer._NormalKind = "normal";
  26043. VertexBuffer._TangentKind = "tangent";
  26044. VertexBuffer._UVKind = "uv";
  26045. VertexBuffer._UV2Kind = "uv2";
  26046. VertexBuffer._UV3Kind = "uv3";
  26047. VertexBuffer._UV4Kind = "uv4";
  26048. VertexBuffer._UV5Kind = "uv5";
  26049. VertexBuffer._UV6Kind = "uv6";
  26050. VertexBuffer._ColorKind = "color";
  26051. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26052. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26053. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26054. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26055. return VertexBuffer;
  26056. }());
  26057. BABYLON.VertexBuffer = VertexBuffer;
  26058. })(BABYLON || (BABYLON = {}));
  26059. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26060. var BABYLON;
  26061. (function (BABYLON) {
  26062. /**
  26063. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26064. */
  26065. var DummyInternalTextureTracker = /** @class */ (function () {
  26066. function DummyInternalTextureTracker() {
  26067. /**
  26068. * Gets or set the previous tracker in the list
  26069. */
  26070. this.previous = null;
  26071. /**
  26072. * Gets or set the next tracker in the list
  26073. */
  26074. this.next = null;
  26075. }
  26076. return DummyInternalTextureTracker;
  26077. }());
  26078. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26079. })(BABYLON || (BABYLON = {}));
  26080. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26081. var BABYLON;
  26082. (function (BABYLON) {
  26083. /**
  26084. * Class used to store data associated with WebGL texture data for the engine
  26085. * This class should not be used directly
  26086. */
  26087. var InternalTexture = /** @class */ (function () {
  26088. /**
  26089. * Creates a new InternalTexture
  26090. * @param engine defines the engine to use
  26091. * @param dataSource defines the type of data that will be used
  26092. */
  26093. function InternalTexture(engine, dataSource) {
  26094. /**
  26095. * Observable called when the texture is loaded
  26096. */
  26097. this.onLoadedObservable = new BABYLON.Observable();
  26098. /**
  26099. * Gets or set the previous tracker in the list
  26100. */
  26101. this.previous = null;
  26102. /**
  26103. * Gets or set the next tracker in the list
  26104. */
  26105. this.next = null;
  26106. // Private
  26107. /** @ignore */
  26108. this._initialSlot = -1;
  26109. /** @ignore */
  26110. this._designatedSlot = -1;
  26111. /** @ignore */
  26112. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26113. /** @ignore */
  26114. this._comparisonFunction = 0;
  26115. /** @ignore */
  26116. this._references = 1;
  26117. this._engine = engine;
  26118. this._dataSource = dataSource;
  26119. this._webGLTexture = engine._createTexture();
  26120. }
  26121. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26122. /**
  26123. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26124. */
  26125. get: function () {
  26126. return this._dataSource;
  26127. },
  26128. enumerable: true,
  26129. configurable: true
  26130. });
  26131. /**
  26132. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26133. */
  26134. InternalTexture.prototype.incrementReferences = function () {
  26135. this._references++;
  26136. };
  26137. /**
  26138. * Change the size of the texture (not the size of the content)
  26139. * @param width defines the new width
  26140. * @param height defines the new height
  26141. * @param depth defines the new depth (1 by default)
  26142. */
  26143. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26144. if (depth === void 0) { depth = 1; }
  26145. this.width = width;
  26146. this.height = height;
  26147. this.depth = depth;
  26148. this.baseWidth = width;
  26149. this.baseHeight = height;
  26150. this.baseDepth = depth;
  26151. this._size = width * height * depth;
  26152. };
  26153. /** @ignore */
  26154. InternalTexture.prototype._rebuild = function () {
  26155. var _this = this;
  26156. var proxy;
  26157. this.isReady = false;
  26158. this._cachedCoordinatesMode = null;
  26159. this._cachedWrapU = null;
  26160. this._cachedWrapV = null;
  26161. this._cachedAnisotropicFilteringLevel = null;
  26162. switch (this._dataSource) {
  26163. case InternalTexture.DATASOURCE_TEMP:
  26164. return;
  26165. case InternalTexture.DATASOURCE_URL:
  26166. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26167. _this.isReady = true;
  26168. }, null, this._buffer, undefined, this.format);
  26169. proxy._swapAndDie(this);
  26170. return;
  26171. case InternalTexture.DATASOURCE_RAW:
  26172. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26173. proxy._swapAndDie(this);
  26174. this.isReady = true;
  26175. return;
  26176. case InternalTexture.DATASOURCE_RAW3D:
  26177. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26178. proxy._swapAndDie(this);
  26179. this.isReady = true;
  26180. return;
  26181. case InternalTexture.DATASOURCE_DYNAMIC:
  26182. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26183. proxy._swapAndDie(this);
  26184. // The engine will make sure to update content so no need to flag it as isReady = true
  26185. return;
  26186. case InternalTexture.DATASOURCE_RENDERTARGET:
  26187. var options = new BABYLON.RenderTargetCreationOptions();
  26188. options.generateDepthBuffer = this._generateDepthBuffer;
  26189. options.generateMipMaps = this.generateMipMaps;
  26190. options.generateStencilBuffer = this._generateStencilBuffer;
  26191. options.samplingMode = this.samplingMode;
  26192. options.type = this.type;
  26193. if (this.isCube) {
  26194. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26195. }
  26196. else {
  26197. var size = {
  26198. width: this.width,
  26199. height: this.height
  26200. };
  26201. proxy = this._engine.createRenderTargetTexture(size, options);
  26202. }
  26203. proxy._swapAndDie(this);
  26204. this.isReady = true;
  26205. return;
  26206. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26207. var depthTextureOptions = {
  26208. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26209. comparisonFunction: this._comparisonFunction,
  26210. generateStencil: this._generateStencilBuffer,
  26211. };
  26212. if (this.isCube) {
  26213. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26214. }
  26215. else {
  26216. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26217. }
  26218. proxy._swapAndDie(this);
  26219. this.isReady = true;
  26220. return;
  26221. case InternalTexture.DATASOURCE_CUBE:
  26222. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26223. _this.isReady = true;
  26224. }, null, this.format, this._extension);
  26225. proxy._swapAndDie(this);
  26226. return;
  26227. case InternalTexture.DATASOURCE_CUBERAW:
  26228. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26229. proxy._swapAndDie(this);
  26230. this.isReady = true;
  26231. return;
  26232. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26233. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26234. if (proxy) {
  26235. proxy._swapAndDie(_this);
  26236. }
  26237. _this.isReady = true;
  26238. }, null, this.format, this._extension);
  26239. return;
  26240. }
  26241. };
  26242. InternalTexture.prototype._swapAndDie = function (target) {
  26243. target._webGLTexture = this._webGLTexture;
  26244. if (this._framebuffer) {
  26245. target._framebuffer = this._framebuffer;
  26246. }
  26247. if (this._depthStencilBuffer) {
  26248. target._depthStencilBuffer = this._depthStencilBuffer;
  26249. }
  26250. if (this._lodTextureHigh) {
  26251. if (target._lodTextureHigh) {
  26252. target._lodTextureHigh.dispose();
  26253. }
  26254. target._lodTextureHigh = this._lodTextureHigh;
  26255. }
  26256. if (this._lodTextureMid) {
  26257. if (target._lodTextureMid) {
  26258. target._lodTextureMid.dispose();
  26259. }
  26260. target._lodTextureMid = this._lodTextureMid;
  26261. }
  26262. if (this._lodTextureLow) {
  26263. if (target._lodTextureLow) {
  26264. target._lodTextureLow.dispose();
  26265. }
  26266. target._lodTextureLow = this._lodTextureLow;
  26267. }
  26268. var cache = this._engine.getLoadedTexturesCache();
  26269. var index = cache.indexOf(this);
  26270. if (index !== -1) {
  26271. cache.splice(index, 1);
  26272. }
  26273. };
  26274. /**
  26275. * Dispose the current allocated resources
  26276. */
  26277. InternalTexture.prototype.dispose = function () {
  26278. if (!this._webGLTexture) {
  26279. return;
  26280. }
  26281. this._references--;
  26282. if (this._references === 0) {
  26283. this._engine._releaseTexture(this);
  26284. this._webGLTexture = null;
  26285. this.previous = null;
  26286. this.next = null;
  26287. }
  26288. };
  26289. /**
  26290. * The source of the texture data is unknown
  26291. */
  26292. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26293. /**
  26294. * Texture data comes from an URL
  26295. */
  26296. InternalTexture.DATASOURCE_URL = 1;
  26297. /**
  26298. * Texture data is only used for temporary storage
  26299. */
  26300. InternalTexture.DATASOURCE_TEMP = 2;
  26301. /**
  26302. * Texture data comes from raw data (ArrayBuffer)
  26303. */
  26304. InternalTexture.DATASOURCE_RAW = 3;
  26305. /**
  26306. * Texture content is dynamic (video or dynamic texture)
  26307. */
  26308. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26309. /**
  26310. * Texture content is generated by rendering to it
  26311. */
  26312. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26313. /**
  26314. * Texture content is part of a multi render target process
  26315. */
  26316. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26317. /**
  26318. * Texture data comes from a cube data file
  26319. */
  26320. InternalTexture.DATASOURCE_CUBE = 7;
  26321. /**
  26322. * Texture data comes from a raw cube data
  26323. */
  26324. InternalTexture.DATASOURCE_CUBERAW = 8;
  26325. /**
  26326. * Texture data come from a prefiltered cube data file
  26327. */
  26328. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26329. /**
  26330. * Texture content is raw 3D data
  26331. */
  26332. InternalTexture.DATASOURCE_RAW3D = 10;
  26333. /**
  26334. * Texture content is a depth texture
  26335. */
  26336. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26337. return InternalTexture;
  26338. }());
  26339. BABYLON.InternalTexture = InternalTexture;
  26340. })(BABYLON || (BABYLON = {}));
  26341. //# sourceMappingURL=babylon.internalTexture.js.map
  26342. var BABYLON;
  26343. (function (BABYLON) {
  26344. var BaseTexture = /** @class */ (function () {
  26345. function BaseTexture(scene) {
  26346. this._hasAlpha = false;
  26347. this.getAlphaFromRGB = false;
  26348. this.level = 1;
  26349. this.coordinatesIndex = 0;
  26350. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26351. /**
  26352. * | Value | Type | Description |
  26353. * | ----- | ------------------ | ----------- |
  26354. * | 0 | CLAMP_ADDRESSMODE | |
  26355. * | 1 | WRAP_ADDRESSMODE | |
  26356. * | 2 | MIRROR_ADDRESSMODE | |
  26357. */
  26358. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26359. /**
  26360. * | Value | Type | Description |
  26361. * | ----- | ------------------ | ----------- |
  26362. * | 0 | CLAMP_ADDRESSMODE | |
  26363. * | 1 | WRAP_ADDRESSMODE | |
  26364. * | 2 | MIRROR_ADDRESSMODE | |
  26365. */
  26366. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26367. /**
  26368. * | Value | Type | Description |
  26369. * | ----- | ------------------ | ----------- |
  26370. * | 0 | CLAMP_ADDRESSMODE | |
  26371. * | 1 | WRAP_ADDRESSMODE | |
  26372. * | 2 | MIRROR_ADDRESSMODE | |
  26373. */
  26374. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26375. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26376. this.isCube = false;
  26377. this.is3D = false;
  26378. this.gammaSpace = true;
  26379. this.invertZ = false;
  26380. this.lodLevelInAlpha = false;
  26381. this.lodGenerationOffset = 0.0;
  26382. this.lodGenerationScale = 0.8;
  26383. this.isRenderTarget = false;
  26384. this.animations = new Array();
  26385. /**
  26386. * An event triggered when the texture is disposed.
  26387. * @type {BABYLON.Observable}
  26388. */
  26389. this.onDisposeObservable = new BABYLON.Observable();
  26390. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26391. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26392. if (this._scene) {
  26393. this._scene.textures.push(this);
  26394. }
  26395. this._uid = null;
  26396. }
  26397. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26398. get: function () {
  26399. return this._hasAlpha;
  26400. },
  26401. set: function (value) {
  26402. if (this._hasAlpha === value) {
  26403. return;
  26404. }
  26405. this._hasAlpha = value;
  26406. if (this._scene) {
  26407. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26408. }
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26414. get: function () {
  26415. return this._coordinatesMode;
  26416. },
  26417. /**
  26418. * How a texture is mapped.
  26419. *
  26420. * | Value | Type | Description |
  26421. * | ----- | ----------------------------------- | ----------- |
  26422. * | 0 | EXPLICIT_MODE | |
  26423. * | 1 | SPHERICAL_MODE | |
  26424. * | 2 | PLANAR_MODE | |
  26425. * | 3 | CUBIC_MODE | |
  26426. * | 4 | PROJECTION_MODE | |
  26427. * | 5 | SKYBOX_MODE | |
  26428. * | 6 | INVCUBIC_MODE | |
  26429. * | 7 | EQUIRECTANGULAR_MODE | |
  26430. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26431. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26432. */
  26433. set: function (value) {
  26434. if (this._coordinatesMode === value) {
  26435. return;
  26436. }
  26437. this._coordinatesMode = value;
  26438. if (this._scene) {
  26439. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26440. }
  26441. },
  26442. enumerable: true,
  26443. configurable: true
  26444. });
  26445. Object.defineProperty(BaseTexture.prototype, "uid", {
  26446. get: function () {
  26447. if (!this._uid) {
  26448. this._uid = BABYLON.Tools.RandomId();
  26449. }
  26450. return this._uid;
  26451. },
  26452. enumerable: true,
  26453. configurable: true
  26454. });
  26455. BaseTexture.prototype.toString = function () {
  26456. return this.name;
  26457. };
  26458. BaseTexture.prototype.getClassName = function () {
  26459. return "BaseTexture";
  26460. };
  26461. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26462. set: function (callback) {
  26463. if (this._onDisposeObserver) {
  26464. this.onDisposeObservable.remove(this._onDisposeObserver);
  26465. }
  26466. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26472. get: function () {
  26473. return true;
  26474. },
  26475. enumerable: true,
  26476. configurable: true
  26477. });
  26478. BaseTexture.prototype.getScene = function () {
  26479. return this._scene;
  26480. };
  26481. BaseTexture.prototype.getTextureMatrix = function () {
  26482. return BABYLON.Matrix.IdentityReadOnly;
  26483. };
  26484. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26485. return BABYLON.Matrix.IdentityReadOnly;
  26486. };
  26487. BaseTexture.prototype.getInternalTexture = function () {
  26488. return this._texture;
  26489. };
  26490. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26491. return !this.isBlocking || this.isReady();
  26492. };
  26493. BaseTexture.prototype.isReady = function () {
  26494. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26495. this.delayLoad();
  26496. return false;
  26497. }
  26498. if (this._texture) {
  26499. return this._texture.isReady;
  26500. }
  26501. return false;
  26502. };
  26503. BaseTexture.prototype.getSize = function () {
  26504. if (this._texture && this._texture.width) {
  26505. return new BABYLON.Size(this._texture.width, this._texture.height);
  26506. }
  26507. if (this._texture && this._texture._size) {
  26508. return new BABYLON.Size(this._texture._size, this._texture._size);
  26509. }
  26510. return BABYLON.Size.Zero();
  26511. };
  26512. BaseTexture.prototype.getBaseSize = function () {
  26513. if (!this.isReady() || !this._texture)
  26514. return BABYLON.Size.Zero();
  26515. if (this._texture._size) {
  26516. return new BABYLON.Size(this._texture._size, this._texture._size);
  26517. }
  26518. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26519. };
  26520. BaseTexture.prototype.scale = function (ratio) {
  26521. };
  26522. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26523. get: function () {
  26524. return false;
  26525. },
  26526. enumerable: true,
  26527. configurable: true
  26528. });
  26529. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26530. if (!this._scene) {
  26531. return null;
  26532. }
  26533. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26534. for (var index = 0; index < texturesCache.length; index++) {
  26535. var texturesCacheEntry = texturesCache[index];
  26536. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26537. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26538. texturesCacheEntry.incrementReferences();
  26539. return texturesCacheEntry;
  26540. }
  26541. }
  26542. }
  26543. return null;
  26544. };
  26545. BaseTexture.prototype._rebuild = function () {
  26546. };
  26547. BaseTexture.prototype.delayLoad = function () {
  26548. };
  26549. BaseTexture.prototype.clone = function () {
  26550. return null;
  26551. };
  26552. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26553. get: function () {
  26554. if (!this._texture) {
  26555. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26556. }
  26557. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26558. },
  26559. enumerable: true,
  26560. configurable: true
  26561. });
  26562. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26563. get: function () {
  26564. if (!this._texture) {
  26565. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26566. }
  26567. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26568. },
  26569. enumerable: true,
  26570. configurable: true
  26571. });
  26572. BaseTexture.prototype.readPixels = function (faceIndex) {
  26573. if (faceIndex === void 0) { faceIndex = 0; }
  26574. if (!this._texture) {
  26575. return null;
  26576. }
  26577. var size = this.getSize();
  26578. var scene = this.getScene();
  26579. if (!scene) {
  26580. return null;
  26581. }
  26582. var engine = scene.getEngine();
  26583. if (this._texture.isCube) {
  26584. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26585. }
  26586. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26587. };
  26588. BaseTexture.prototype.releaseInternalTexture = function () {
  26589. if (this._texture) {
  26590. this._texture.dispose();
  26591. this._texture = null;
  26592. }
  26593. };
  26594. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26595. get: function () {
  26596. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26597. return null;
  26598. }
  26599. if (!this._texture._sphericalPolynomial) {
  26600. this._texture._sphericalPolynomial =
  26601. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26602. }
  26603. return this._texture._sphericalPolynomial;
  26604. },
  26605. set: function (value) {
  26606. if (this._texture) {
  26607. this._texture._sphericalPolynomial = value;
  26608. }
  26609. },
  26610. enumerable: true,
  26611. configurable: true
  26612. });
  26613. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26614. get: function () {
  26615. if (this._texture) {
  26616. return this._texture._lodTextureHigh;
  26617. }
  26618. return null;
  26619. },
  26620. enumerable: true,
  26621. configurable: true
  26622. });
  26623. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26624. get: function () {
  26625. if (this._texture) {
  26626. return this._texture._lodTextureMid;
  26627. }
  26628. return null;
  26629. },
  26630. enumerable: true,
  26631. configurable: true
  26632. });
  26633. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26634. get: function () {
  26635. if (this._texture) {
  26636. return this._texture._lodTextureLow;
  26637. }
  26638. return null;
  26639. },
  26640. enumerable: true,
  26641. configurable: true
  26642. });
  26643. BaseTexture.prototype.dispose = function () {
  26644. if (!this._scene) {
  26645. return;
  26646. }
  26647. // Animations
  26648. this._scene.stopAnimation(this);
  26649. // Remove from scene
  26650. this._scene._removePendingData(this);
  26651. var index = this._scene.textures.indexOf(this);
  26652. if (index >= 0) {
  26653. this._scene.textures.splice(index, 1);
  26654. }
  26655. if (this._texture === undefined) {
  26656. return;
  26657. }
  26658. // Release
  26659. this.releaseInternalTexture();
  26660. // Callback
  26661. this.onDisposeObservable.notifyObservers(this);
  26662. this.onDisposeObservable.clear();
  26663. };
  26664. BaseTexture.prototype.serialize = function () {
  26665. if (!this.name) {
  26666. return null;
  26667. }
  26668. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26669. // Animations
  26670. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26671. return serializationObject;
  26672. };
  26673. BaseTexture.WhenAllReady = function (textures, callback) {
  26674. var numRemaining = textures.length;
  26675. if (numRemaining === 0) {
  26676. callback();
  26677. return;
  26678. }
  26679. var _loop_1 = function () {
  26680. texture = textures[i];
  26681. if (texture.isReady()) {
  26682. if (--numRemaining === 0) {
  26683. callback();
  26684. }
  26685. }
  26686. else {
  26687. onLoadObservable = texture.onLoadObservable;
  26688. var onLoadCallback_1 = function () {
  26689. onLoadObservable.removeCallback(onLoadCallback_1);
  26690. if (--numRemaining === 0) {
  26691. callback();
  26692. }
  26693. };
  26694. onLoadObservable.add(onLoadCallback_1);
  26695. }
  26696. };
  26697. var texture, onLoadObservable;
  26698. for (var i = 0; i < textures.length; i++) {
  26699. _loop_1();
  26700. }
  26701. };
  26702. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26703. __decorate([
  26704. BABYLON.serialize()
  26705. ], BaseTexture.prototype, "name", void 0);
  26706. __decorate([
  26707. BABYLON.serialize("hasAlpha")
  26708. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26709. __decorate([
  26710. BABYLON.serialize()
  26711. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26712. __decorate([
  26713. BABYLON.serialize()
  26714. ], BaseTexture.prototype, "level", void 0);
  26715. __decorate([
  26716. BABYLON.serialize()
  26717. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26718. __decorate([
  26719. BABYLON.serialize("coordinatesMode")
  26720. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26721. __decorate([
  26722. BABYLON.serialize()
  26723. ], BaseTexture.prototype, "wrapU", void 0);
  26724. __decorate([
  26725. BABYLON.serialize()
  26726. ], BaseTexture.prototype, "wrapV", void 0);
  26727. __decorate([
  26728. BABYLON.serialize()
  26729. ], BaseTexture.prototype, "wrapR", void 0);
  26730. __decorate([
  26731. BABYLON.serialize()
  26732. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26733. __decorate([
  26734. BABYLON.serialize()
  26735. ], BaseTexture.prototype, "isCube", void 0);
  26736. __decorate([
  26737. BABYLON.serialize()
  26738. ], BaseTexture.prototype, "is3D", void 0);
  26739. __decorate([
  26740. BABYLON.serialize()
  26741. ], BaseTexture.prototype, "gammaSpace", void 0);
  26742. __decorate([
  26743. BABYLON.serialize()
  26744. ], BaseTexture.prototype, "invertZ", void 0);
  26745. __decorate([
  26746. BABYLON.serialize()
  26747. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26748. __decorate([
  26749. BABYLON.serialize()
  26750. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26751. __decorate([
  26752. BABYLON.serialize()
  26753. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26754. __decorate([
  26755. BABYLON.serialize()
  26756. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26757. return BaseTexture;
  26758. }());
  26759. BABYLON.BaseTexture = BaseTexture;
  26760. })(BABYLON || (BABYLON = {}));
  26761. //# sourceMappingURL=babylon.baseTexture.js.map
  26762. var BABYLON;
  26763. (function (BABYLON) {
  26764. var Texture = /** @class */ (function (_super) {
  26765. __extends(Texture, _super);
  26766. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26767. if (noMipmap === void 0) { noMipmap = false; }
  26768. if (invertY === void 0) { invertY = true; }
  26769. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26770. if (onLoad === void 0) { onLoad = null; }
  26771. if (onError === void 0) { onError = null; }
  26772. if (buffer === void 0) { buffer = null; }
  26773. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26774. var _this = _super.call(this, scene) || this;
  26775. _this.uOffset = 0;
  26776. _this.vOffset = 0;
  26777. _this.uScale = 1.0;
  26778. _this.vScale = 1.0;
  26779. _this.uAng = 0;
  26780. _this.vAng = 0;
  26781. _this.wAng = 0;
  26782. _this._isBlocking = true;
  26783. _this.name = url || "";
  26784. _this.url = url;
  26785. _this._noMipmap = noMipmap;
  26786. _this._invertY = invertY;
  26787. _this._samplingMode = samplingMode;
  26788. _this._buffer = buffer;
  26789. _this._deleteBuffer = deleteBuffer;
  26790. if (format) {
  26791. _this._format = format;
  26792. }
  26793. scene = _this.getScene();
  26794. if (!scene) {
  26795. return _this;
  26796. }
  26797. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26798. var load = function () {
  26799. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26800. _this.onLoadObservable.notifyObservers(_this);
  26801. }
  26802. if (onLoad) {
  26803. onLoad();
  26804. }
  26805. if (!_this.isBlocking && scene) {
  26806. scene.resetCachedMaterial();
  26807. }
  26808. };
  26809. if (!_this.url) {
  26810. _this._delayedOnLoad = load;
  26811. _this._delayedOnError = onError;
  26812. return _this;
  26813. }
  26814. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26815. if (!_this._texture) {
  26816. if (!scene.useDelayedTextureLoading) {
  26817. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26818. if (deleteBuffer) {
  26819. delete _this._buffer;
  26820. }
  26821. }
  26822. else {
  26823. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26824. _this._delayedOnLoad = load;
  26825. _this._delayedOnError = onError;
  26826. }
  26827. }
  26828. else {
  26829. if (_this._texture.isReady) {
  26830. BABYLON.Tools.SetImmediate(function () { return load(); });
  26831. }
  26832. else {
  26833. _this._texture.onLoadedObservable.add(load);
  26834. }
  26835. }
  26836. return _this;
  26837. }
  26838. Object.defineProperty(Texture.prototype, "noMipmap", {
  26839. get: function () {
  26840. return this._noMipmap;
  26841. },
  26842. enumerable: true,
  26843. configurable: true
  26844. });
  26845. Object.defineProperty(Texture.prototype, "isBlocking", {
  26846. get: function () {
  26847. return this._isBlocking;
  26848. },
  26849. set: function (value) {
  26850. this._isBlocking = value;
  26851. },
  26852. enumerable: true,
  26853. configurable: true
  26854. });
  26855. Object.defineProperty(Texture.prototype, "samplingMode", {
  26856. get: function () {
  26857. return this._samplingMode;
  26858. },
  26859. enumerable: true,
  26860. configurable: true
  26861. });
  26862. Texture.prototype.updateURL = function (url) {
  26863. this.url = url;
  26864. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26865. this.delayLoad();
  26866. };
  26867. Texture.prototype.delayLoad = function () {
  26868. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26869. return;
  26870. }
  26871. var scene = this.getScene();
  26872. if (!scene) {
  26873. return;
  26874. }
  26875. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26876. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26877. if (!this._texture) {
  26878. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26879. if (this._deleteBuffer) {
  26880. delete this._buffer;
  26881. }
  26882. }
  26883. else {
  26884. if (this._delayedOnLoad) {
  26885. if (this._texture.isReady) {
  26886. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26887. }
  26888. else {
  26889. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26890. }
  26891. }
  26892. }
  26893. this._delayedOnLoad = null;
  26894. this._delayedOnError = null;
  26895. };
  26896. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26897. if (!this._texture) {
  26898. return;
  26899. }
  26900. var scene = this.getScene();
  26901. if (!scene) {
  26902. return;
  26903. }
  26904. this._samplingMode = samplingMode;
  26905. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26906. };
  26907. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26908. x *= this.uScale;
  26909. y *= this.vScale;
  26910. x -= 0.5 * this.uScale;
  26911. y -= 0.5 * this.vScale;
  26912. z -= 0.5;
  26913. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26914. t.x += 0.5 * this.uScale + this.uOffset;
  26915. t.y += 0.5 * this.vScale + this.vOffset;
  26916. t.z += 0.5;
  26917. };
  26918. Texture.prototype.getTextureMatrix = function () {
  26919. var _this = this;
  26920. if (this.uOffset === this._cachedUOffset &&
  26921. this.vOffset === this._cachedVOffset &&
  26922. this.uScale === this._cachedUScale &&
  26923. this.vScale === this._cachedVScale &&
  26924. this.uAng === this._cachedUAng &&
  26925. this.vAng === this._cachedVAng &&
  26926. this.wAng === this._cachedWAng) {
  26927. return this._cachedTextureMatrix;
  26928. }
  26929. this._cachedUOffset = this.uOffset;
  26930. this._cachedVOffset = this.vOffset;
  26931. this._cachedUScale = this.uScale;
  26932. this._cachedVScale = this.vScale;
  26933. this._cachedUAng = this.uAng;
  26934. this._cachedVAng = this.vAng;
  26935. this._cachedWAng = this.wAng;
  26936. if (!this._cachedTextureMatrix) {
  26937. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26938. this._rowGenerationMatrix = new BABYLON.Matrix();
  26939. this._t0 = BABYLON.Vector3.Zero();
  26940. this._t1 = BABYLON.Vector3.Zero();
  26941. this._t2 = BABYLON.Vector3.Zero();
  26942. }
  26943. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26944. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26945. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26946. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26947. this._t1.subtractInPlace(this._t0);
  26948. this._t2.subtractInPlace(this._t0);
  26949. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26950. this._cachedTextureMatrix.m[0] = this._t1.x;
  26951. this._cachedTextureMatrix.m[1] = this._t1.y;
  26952. this._cachedTextureMatrix.m[2] = this._t1.z;
  26953. this._cachedTextureMatrix.m[4] = this._t2.x;
  26954. this._cachedTextureMatrix.m[5] = this._t2.y;
  26955. this._cachedTextureMatrix.m[6] = this._t2.z;
  26956. this._cachedTextureMatrix.m[8] = this._t0.x;
  26957. this._cachedTextureMatrix.m[9] = this._t0.y;
  26958. this._cachedTextureMatrix.m[10] = this._t0.z;
  26959. var scene = this.getScene();
  26960. if (!scene) {
  26961. return this._cachedTextureMatrix;
  26962. }
  26963. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26964. return mat.hasTexture(_this);
  26965. });
  26966. return this._cachedTextureMatrix;
  26967. };
  26968. Texture.prototype.getReflectionTextureMatrix = function () {
  26969. var _this = this;
  26970. var scene = this.getScene();
  26971. if (!scene) {
  26972. return this._cachedTextureMatrix;
  26973. }
  26974. if (this.uOffset === this._cachedUOffset &&
  26975. this.vOffset === this._cachedVOffset &&
  26976. this.uScale === this._cachedUScale &&
  26977. this.vScale === this._cachedVScale &&
  26978. this.coordinatesMode === this._cachedCoordinatesMode) {
  26979. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26980. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26981. return this._cachedTextureMatrix;
  26982. }
  26983. }
  26984. else {
  26985. return this._cachedTextureMatrix;
  26986. }
  26987. }
  26988. if (!this._cachedTextureMatrix) {
  26989. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26990. }
  26991. if (!this._projectionModeMatrix) {
  26992. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26993. }
  26994. this._cachedUOffset = this.uOffset;
  26995. this._cachedVOffset = this.vOffset;
  26996. this._cachedUScale = this.uScale;
  26997. this._cachedVScale = this.vScale;
  26998. this._cachedCoordinatesMode = this.coordinatesMode;
  26999. switch (this.coordinatesMode) {
  27000. case Texture.PLANAR_MODE:
  27001. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27002. this._cachedTextureMatrix[0] = this.uScale;
  27003. this._cachedTextureMatrix[5] = this.vScale;
  27004. this._cachedTextureMatrix[12] = this.uOffset;
  27005. this._cachedTextureMatrix[13] = this.vOffset;
  27006. break;
  27007. case Texture.PROJECTION_MODE:
  27008. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27009. this._projectionModeMatrix.m[0] = 0.5;
  27010. this._projectionModeMatrix.m[5] = -0.5;
  27011. this._projectionModeMatrix.m[10] = 0.0;
  27012. this._projectionModeMatrix.m[12] = 0.5;
  27013. this._projectionModeMatrix.m[13] = 0.5;
  27014. this._projectionModeMatrix.m[14] = 1.0;
  27015. this._projectionModeMatrix.m[15] = 1.0;
  27016. var projectionMatrix = scene.getProjectionMatrix();
  27017. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27018. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27019. break;
  27020. default:
  27021. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27022. break;
  27023. }
  27024. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27025. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27026. });
  27027. return this._cachedTextureMatrix;
  27028. };
  27029. Texture.prototype.clone = function () {
  27030. var _this = this;
  27031. return BABYLON.SerializationHelper.Clone(function () {
  27032. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27033. }, this);
  27034. };
  27035. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27036. get: function () {
  27037. if (!this._onLoadObservable) {
  27038. this._onLoadObservable = new BABYLON.Observable();
  27039. }
  27040. return this._onLoadObservable;
  27041. },
  27042. enumerable: true,
  27043. configurable: true
  27044. });
  27045. Texture.prototype.serialize = function () {
  27046. var serializationObject = _super.prototype.serialize.call(this);
  27047. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27048. serializationObject.base64String = this._buffer;
  27049. serializationObject.name = serializationObject.name.replace("data:", "");
  27050. }
  27051. return serializationObject;
  27052. };
  27053. Texture.prototype.getClassName = function () {
  27054. return "Texture";
  27055. };
  27056. Texture.prototype.dispose = function () {
  27057. _super.prototype.dispose.call(this);
  27058. if (this.onLoadObservable) {
  27059. this.onLoadObservable.clear();
  27060. this._onLoadObservable = null;
  27061. }
  27062. this._delayedOnLoad = null;
  27063. this._delayedOnError = null;
  27064. };
  27065. // Statics
  27066. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27067. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27068. if (onLoad === void 0) { onLoad = null; }
  27069. if (onError === void 0) { onError = null; }
  27070. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27071. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27072. };
  27073. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27074. if (parsedTexture.customType) {
  27075. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27076. // Update Sampling Mode
  27077. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27078. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27079. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27080. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27081. }
  27082. }
  27083. return parsedCustomTexture;
  27084. }
  27085. if (parsedTexture.isCube) {
  27086. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27087. }
  27088. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27089. return null;
  27090. }
  27091. var texture = BABYLON.SerializationHelper.Parse(function () {
  27092. var generateMipMaps = true;
  27093. if (parsedTexture.noMipmap) {
  27094. generateMipMaps = false;
  27095. }
  27096. if (parsedTexture.mirrorPlane) {
  27097. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27098. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27099. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27100. return mirrorTexture;
  27101. }
  27102. else if (parsedTexture.isRenderTarget) {
  27103. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27104. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27105. return renderTargetTexture;
  27106. }
  27107. else {
  27108. var texture;
  27109. if (parsedTexture.base64String) {
  27110. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27111. }
  27112. else {
  27113. var url = rootUrl + parsedTexture.name;
  27114. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27115. url = parsedTexture.url;
  27116. }
  27117. texture = new Texture(url, scene, !generateMipMaps);
  27118. }
  27119. return texture;
  27120. }
  27121. }, parsedTexture, scene);
  27122. // Update Sampling Mode
  27123. if (parsedTexture.samplingMode) {
  27124. var sampling = parsedTexture.samplingMode;
  27125. if (texture._samplingMode !== sampling) {
  27126. texture.updateSamplingMode(sampling);
  27127. }
  27128. }
  27129. // Animations
  27130. if (parsedTexture.animations) {
  27131. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27132. var parsedAnimation = parsedTexture.animations[animationIndex];
  27133. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27134. }
  27135. }
  27136. return texture;
  27137. };
  27138. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27139. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27140. if (noMipmap === void 0) { noMipmap = false; }
  27141. if (invertY === void 0) { invertY = true; }
  27142. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27143. if (onLoad === void 0) { onLoad = null; }
  27144. if (onError === void 0) { onError = null; }
  27145. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27146. if (name.substr(0, 5) !== "data:") {
  27147. name = "data:" + name;
  27148. }
  27149. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27150. };
  27151. // Constants
  27152. Texture.NEAREST_SAMPLINGMODE = 1;
  27153. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27154. Texture.BILINEAR_SAMPLINGMODE = 2;
  27155. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27156. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27157. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27158. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27159. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27160. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27161. Texture.NEAREST_LINEAR = 7;
  27162. Texture.NEAREST_NEAREST = 8;
  27163. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27164. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27165. Texture.LINEAR_LINEAR = 11;
  27166. Texture.LINEAR_NEAREST = 12;
  27167. Texture.EXPLICIT_MODE = 0;
  27168. Texture.SPHERICAL_MODE = 1;
  27169. Texture.PLANAR_MODE = 2;
  27170. Texture.CUBIC_MODE = 3;
  27171. Texture.PROJECTION_MODE = 4;
  27172. Texture.SKYBOX_MODE = 5;
  27173. Texture.INVCUBIC_MODE = 6;
  27174. Texture.EQUIRECTANGULAR_MODE = 7;
  27175. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27176. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27177. Texture.CLAMP_ADDRESSMODE = 0;
  27178. Texture.WRAP_ADDRESSMODE = 1;
  27179. Texture.MIRROR_ADDRESSMODE = 2;
  27180. /**
  27181. * 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
  27182. */
  27183. Texture.UseSerializedUrlIfAny = false;
  27184. __decorate([
  27185. BABYLON.serialize()
  27186. ], Texture.prototype, "url", void 0);
  27187. __decorate([
  27188. BABYLON.serialize()
  27189. ], Texture.prototype, "uOffset", void 0);
  27190. __decorate([
  27191. BABYLON.serialize()
  27192. ], Texture.prototype, "vOffset", void 0);
  27193. __decorate([
  27194. BABYLON.serialize()
  27195. ], Texture.prototype, "uScale", void 0);
  27196. __decorate([
  27197. BABYLON.serialize()
  27198. ], Texture.prototype, "vScale", void 0);
  27199. __decorate([
  27200. BABYLON.serialize()
  27201. ], Texture.prototype, "uAng", void 0);
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], Texture.prototype, "vAng", void 0);
  27205. __decorate([
  27206. BABYLON.serialize()
  27207. ], Texture.prototype, "wAng", void 0);
  27208. __decorate([
  27209. BABYLON.serialize()
  27210. ], Texture.prototype, "isBlocking", null);
  27211. return Texture;
  27212. }(BABYLON.BaseTexture));
  27213. BABYLON.Texture = Texture;
  27214. })(BABYLON || (BABYLON = {}));
  27215. //# sourceMappingURL=babylon.texture.js.map
  27216. var BABYLON;
  27217. (function (BABYLON) {
  27218. var _InstancesBatch = /** @class */ (function () {
  27219. function _InstancesBatch() {
  27220. this.mustReturn = false;
  27221. this.visibleInstances = new Array();
  27222. this.renderSelf = new Array();
  27223. }
  27224. return _InstancesBatch;
  27225. }());
  27226. BABYLON._InstancesBatch = _InstancesBatch;
  27227. var Mesh = /** @class */ (function (_super) {
  27228. __extends(Mesh, _super);
  27229. /**
  27230. * @constructor
  27231. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27232. * @param {Scene} scene The scene to add this mesh to.
  27233. * @param {Node} parent The parent of this mesh, if it has one
  27234. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27235. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27236. * When false, achieved by calling a clone(), also passing False.
  27237. * This will make creation of children, recursive.
  27238. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27239. */
  27240. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27241. if (scene === void 0) { scene = null; }
  27242. if (parent === void 0) { parent = null; }
  27243. if (source === void 0) { source = null; }
  27244. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27245. var _this = _super.call(this, name, scene) || this;
  27246. // Events
  27247. /**
  27248. * An event triggered before rendering the mesh
  27249. * @type {BABYLON.Observable}
  27250. */
  27251. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27252. /**
  27253. * An event triggered after rendering the mesh
  27254. * @type {BABYLON.Observable}
  27255. */
  27256. _this.onAfterRenderObservable = new BABYLON.Observable();
  27257. /**
  27258. * An event triggered before drawing the mesh
  27259. * @type {BABYLON.Observable}
  27260. */
  27261. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27262. // Members
  27263. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27264. _this.instances = new Array();
  27265. _this._LODLevels = new Array();
  27266. _this._visibleInstances = {};
  27267. _this._renderIdForInstances = new Array();
  27268. _this._batchCache = new _InstancesBatch();
  27269. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27270. // Use by builder only to know what orientation were the mesh build in.
  27271. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27272. _this.overrideMaterialSideOrientation = null;
  27273. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27274. // Will be used to save a source mesh reference, If any
  27275. _this._source = null;
  27276. scene = _this.getScene();
  27277. if (source) {
  27278. // Source mesh
  27279. _this._source = source;
  27280. // Geometry
  27281. if (source._geometry) {
  27282. source._geometry.applyToMesh(_this);
  27283. }
  27284. // Deep copy
  27285. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27286. // Metadata
  27287. if (source.metadata && source.metadata.clone) {
  27288. _this.metadata = source.metadata.clone();
  27289. }
  27290. else {
  27291. _this.metadata = source.metadata;
  27292. }
  27293. // Tags
  27294. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27295. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27296. }
  27297. // Parent
  27298. _this.parent = source.parent;
  27299. // Pivot
  27300. _this.setPivotMatrix(source.getPivotMatrix());
  27301. _this.id = name + "." + source.id;
  27302. // Material
  27303. _this.material = source.material;
  27304. var index;
  27305. if (!doNotCloneChildren) {
  27306. // Children
  27307. var directDescendants = source.getDescendants(true);
  27308. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27309. var child = directDescendants[index_1];
  27310. if (child.clone) {
  27311. child.clone(name + "." + child.name, _this);
  27312. }
  27313. }
  27314. }
  27315. // Physics clone
  27316. var physicsEngine = _this.getScene().getPhysicsEngine();
  27317. if (clonePhysicsImpostor && physicsEngine) {
  27318. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27319. if (impostor) {
  27320. _this.physicsImpostor = impostor.clone(_this);
  27321. }
  27322. }
  27323. // Particles
  27324. for (index = 0; index < scene.particleSystems.length; index++) {
  27325. var system = scene.particleSystems[index];
  27326. if (system.emitter === source) {
  27327. system.clone(system.name, _this);
  27328. }
  27329. }
  27330. _this.computeWorldMatrix(true);
  27331. }
  27332. // Parent
  27333. if (parent !== null) {
  27334. _this.parent = parent;
  27335. }
  27336. return _this;
  27337. }
  27338. Object.defineProperty(Mesh, "FRONTSIDE", {
  27339. /**
  27340. * Mesh side orientation : usually the external or front surface
  27341. */
  27342. get: function () {
  27343. return Mesh._FRONTSIDE;
  27344. },
  27345. enumerable: true,
  27346. configurable: true
  27347. });
  27348. Object.defineProperty(Mesh, "BACKSIDE", {
  27349. /**
  27350. * Mesh side orientation : usually the internal or back surface
  27351. */
  27352. get: function () {
  27353. return Mesh._BACKSIDE;
  27354. },
  27355. enumerable: true,
  27356. configurable: true
  27357. });
  27358. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27359. /**
  27360. * Mesh side orientation : both internal and external or front and back surfaces
  27361. */
  27362. get: function () {
  27363. return Mesh._DOUBLESIDE;
  27364. },
  27365. enumerable: true,
  27366. configurable: true
  27367. });
  27368. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27369. /**
  27370. * Mesh side orientation : by default, `FRONTSIDE`
  27371. */
  27372. get: function () {
  27373. return Mesh._DEFAULTSIDE;
  27374. },
  27375. enumerable: true,
  27376. configurable: true
  27377. });
  27378. Object.defineProperty(Mesh, "NO_CAP", {
  27379. /**
  27380. * Mesh cap setting : no cap
  27381. */
  27382. get: function () {
  27383. return Mesh._NO_CAP;
  27384. },
  27385. enumerable: true,
  27386. configurable: true
  27387. });
  27388. Object.defineProperty(Mesh, "CAP_START", {
  27389. /**
  27390. * Mesh cap setting : one cap at the beginning of the mesh
  27391. */
  27392. get: function () {
  27393. return Mesh._CAP_START;
  27394. },
  27395. enumerable: true,
  27396. configurable: true
  27397. });
  27398. Object.defineProperty(Mesh, "CAP_END", {
  27399. /**
  27400. * Mesh cap setting : one cap at the end of the mesh
  27401. */
  27402. get: function () {
  27403. return Mesh._CAP_END;
  27404. },
  27405. enumerable: true,
  27406. configurable: true
  27407. });
  27408. Object.defineProperty(Mesh, "CAP_ALL", {
  27409. /**
  27410. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27411. */
  27412. get: function () {
  27413. return Mesh._CAP_ALL;
  27414. },
  27415. enumerable: true,
  27416. configurable: true
  27417. });
  27418. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27419. set: function (callback) {
  27420. if (this._onBeforeDrawObserver) {
  27421. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27422. }
  27423. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27424. },
  27425. enumerable: true,
  27426. configurable: true
  27427. });
  27428. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27429. get: function () {
  27430. return this._morphTargetManager;
  27431. },
  27432. set: function (value) {
  27433. if (this._morphTargetManager === value) {
  27434. return;
  27435. }
  27436. this._morphTargetManager = value;
  27437. this._syncGeometryWithMorphTargetManager();
  27438. },
  27439. enumerable: true,
  27440. configurable: true
  27441. });
  27442. Object.defineProperty(Mesh.prototype, "source", {
  27443. get: function () {
  27444. return this._source;
  27445. },
  27446. enumerable: true,
  27447. configurable: true
  27448. });
  27449. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27450. get: function () {
  27451. return this._unIndexed;
  27452. },
  27453. set: function (value) {
  27454. if (this._unIndexed !== value) {
  27455. this._unIndexed = value;
  27456. this._markSubMeshesAsAttributesDirty();
  27457. }
  27458. },
  27459. enumerable: true,
  27460. configurable: true
  27461. });
  27462. // Methods
  27463. /**
  27464. * Returns the string "Mesh".
  27465. */
  27466. Mesh.prototype.getClassName = function () {
  27467. return "Mesh";
  27468. };
  27469. /**
  27470. * Returns a string.
  27471. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27472. */
  27473. Mesh.prototype.toString = function (fullDetails) {
  27474. var ret = _super.prototype.toString.call(this, fullDetails);
  27475. ret += ", n vertices: " + this.getTotalVertices();
  27476. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27477. if (this.animations) {
  27478. for (var i = 0; i < this.animations.length; i++) {
  27479. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27480. }
  27481. }
  27482. if (fullDetails) {
  27483. if (this._geometry) {
  27484. var ib = this.getIndices();
  27485. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27486. if (vb && ib) {
  27487. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27488. }
  27489. }
  27490. else {
  27491. ret += ", flat shading: UNKNOWN";
  27492. }
  27493. }
  27494. return ret;
  27495. };
  27496. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27497. /**
  27498. * True if the mesh has some Levels Of Details (LOD).
  27499. * Returns a boolean.
  27500. */
  27501. get: function () {
  27502. return this._LODLevels.length > 0;
  27503. },
  27504. enumerable: true,
  27505. configurable: true
  27506. });
  27507. /**
  27508. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27509. * @returns an array of {BABYLON.MeshLODLevel}
  27510. */
  27511. Mesh.prototype.getLODLevels = function () {
  27512. return this._LODLevels;
  27513. };
  27514. Mesh.prototype._sortLODLevels = function () {
  27515. this._LODLevels.sort(function (a, b) {
  27516. if (a.distance < b.distance) {
  27517. return 1;
  27518. }
  27519. if (a.distance > b.distance) {
  27520. return -1;
  27521. }
  27522. return 0;
  27523. });
  27524. };
  27525. /**
  27526. * Add a mesh as LOD level triggered at the given distance.
  27527. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27528. * @param {number} distance The distance from the center of the object to show this level
  27529. * @param {Mesh} mesh The mesh to be added as LOD level
  27530. * @return {Mesh} This mesh (for chaining)
  27531. */
  27532. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27533. if (mesh && mesh._masterMesh) {
  27534. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27535. return this;
  27536. }
  27537. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27538. this._LODLevels.push(level);
  27539. if (mesh) {
  27540. mesh._masterMesh = this;
  27541. }
  27542. this._sortLODLevels();
  27543. return this;
  27544. };
  27545. /**
  27546. * Returns the LOD level mesh at the passed distance or null if not found.
  27547. * It is related to the method `addLODLevel(distance, mesh)`.
  27548. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27549. * Returns an object Mesh or `null`.
  27550. */
  27551. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27552. for (var index = 0; index < this._LODLevels.length; index++) {
  27553. var level = this._LODLevels[index];
  27554. if (level.distance === distance) {
  27555. return level.mesh;
  27556. }
  27557. }
  27558. return null;
  27559. };
  27560. /**
  27561. * Remove a mesh from the LOD array
  27562. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27563. * @param {Mesh} mesh The mesh to be removed.
  27564. * @return {Mesh} This mesh (for chaining)
  27565. */
  27566. Mesh.prototype.removeLODLevel = function (mesh) {
  27567. for (var index = 0; index < this._LODLevels.length; index++) {
  27568. if (this._LODLevels[index].mesh === mesh) {
  27569. this._LODLevels.splice(index, 1);
  27570. if (mesh) {
  27571. mesh._masterMesh = null;
  27572. }
  27573. }
  27574. }
  27575. this._sortLODLevels();
  27576. return this;
  27577. };
  27578. /**
  27579. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27580. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27581. */
  27582. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27583. if (!this._LODLevels || this._LODLevels.length === 0) {
  27584. return this;
  27585. }
  27586. var bSphere;
  27587. if (boundingSphere) {
  27588. bSphere = boundingSphere;
  27589. }
  27590. else {
  27591. var boundingInfo = this.getBoundingInfo();
  27592. bSphere = boundingInfo.boundingSphere;
  27593. }
  27594. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27595. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27596. if (this.onLODLevelSelection) {
  27597. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27598. }
  27599. return this;
  27600. }
  27601. for (var index = 0; index < this._LODLevels.length; index++) {
  27602. var level = this._LODLevels[index];
  27603. if (level.distance < distanceToCamera) {
  27604. if (level.mesh) {
  27605. level.mesh._preActivate();
  27606. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27607. }
  27608. if (this.onLODLevelSelection) {
  27609. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27610. }
  27611. return level.mesh;
  27612. }
  27613. }
  27614. if (this.onLODLevelSelection) {
  27615. this.onLODLevelSelection(distanceToCamera, this, this);
  27616. }
  27617. return this;
  27618. };
  27619. Object.defineProperty(Mesh.prototype, "geometry", {
  27620. /**
  27621. * Returns the mesh internal Geometry object.
  27622. */
  27623. get: function () {
  27624. return this._geometry;
  27625. },
  27626. enumerable: true,
  27627. configurable: true
  27628. });
  27629. /**
  27630. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27631. */
  27632. Mesh.prototype.getTotalVertices = function () {
  27633. if (this._geometry === null || this._geometry === undefined) {
  27634. return 0;
  27635. }
  27636. return this._geometry.getTotalVertices();
  27637. };
  27638. /**
  27639. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27640. * 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.
  27641. * You can force the copy with forceCopy === true
  27642. * Returns null if the mesh has no geometry or no vertex buffer.
  27643. * Possible `kind` values :
  27644. * - BABYLON.VertexBuffer.PositionKind
  27645. * - BABYLON.VertexBuffer.UVKind
  27646. * - BABYLON.VertexBuffer.UV2Kind
  27647. * - BABYLON.VertexBuffer.UV3Kind
  27648. * - BABYLON.VertexBuffer.UV4Kind
  27649. * - BABYLON.VertexBuffer.UV5Kind
  27650. * - BABYLON.VertexBuffer.UV6Kind
  27651. * - BABYLON.VertexBuffer.ColorKind
  27652. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27653. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27654. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27655. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27656. */
  27657. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27658. if (!this._geometry) {
  27659. return null;
  27660. }
  27661. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27662. };
  27663. /**
  27664. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27665. * Returns `null` if the mesh has no geometry.
  27666. * Possible `kind` values :
  27667. * - BABYLON.VertexBuffer.PositionKind
  27668. * - BABYLON.VertexBuffer.UVKind
  27669. * - BABYLON.VertexBuffer.UV2Kind
  27670. * - BABYLON.VertexBuffer.UV3Kind
  27671. * - BABYLON.VertexBuffer.UV4Kind
  27672. * - BABYLON.VertexBuffer.UV5Kind
  27673. * - BABYLON.VertexBuffer.UV6Kind
  27674. * - BABYLON.VertexBuffer.ColorKind
  27675. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27676. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27677. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27678. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27679. */
  27680. Mesh.prototype.getVertexBuffer = function (kind) {
  27681. if (!this._geometry) {
  27682. return null;
  27683. }
  27684. return this._geometry.getVertexBuffer(kind);
  27685. };
  27686. /**
  27687. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27688. * Possible `kind` values :
  27689. * - BABYLON.VertexBuffer.PositionKind
  27690. * - BABYLON.VertexBuffer.UVKind
  27691. * - BABYLON.VertexBuffer.UV2Kind
  27692. * - BABYLON.VertexBuffer.UV3Kind
  27693. * - BABYLON.VertexBuffer.UV4Kind
  27694. * - BABYLON.VertexBuffer.UV5Kind
  27695. * - BABYLON.VertexBuffer.UV6Kind
  27696. * - BABYLON.VertexBuffer.ColorKind
  27697. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27698. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27699. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27700. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27701. */
  27702. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27703. if (!this._geometry) {
  27704. if (this._delayInfo) {
  27705. return this._delayInfo.indexOf(kind) !== -1;
  27706. }
  27707. return false;
  27708. }
  27709. return this._geometry.isVerticesDataPresent(kind);
  27710. };
  27711. /**
  27712. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27713. * Possible `kind` values :
  27714. * - BABYLON.VertexBuffer.PositionKind
  27715. * - BABYLON.VertexBuffer.UVKind
  27716. * - BABYLON.VertexBuffer.UV2Kind
  27717. * - BABYLON.VertexBuffer.UV3Kind
  27718. * - BABYLON.VertexBuffer.UV4Kind
  27719. * - BABYLON.VertexBuffer.UV5Kind
  27720. * - BABYLON.VertexBuffer.UV6Kind
  27721. * - BABYLON.VertexBuffer.ColorKind
  27722. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27723. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27724. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27725. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27726. */
  27727. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27728. if (!this._geometry) {
  27729. if (this._delayInfo) {
  27730. return this._delayInfo.indexOf(kind) !== -1;
  27731. }
  27732. return false;
  27733. }
  27734. return this._geometry.isVertexBufferUpdatable(kind);
  27735. };
  27736. /**
  27737. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27738. * Possible `kind` values :
  27739. * - BABYLON.VertexBuffer.PositionKind
  27740. * - BABYLON.VertexBuffer.UVKind
  27741. * - BABYLON.VertexBuffer.UV2Kind
  27742. * - BABYLON.VertexBuffer.UV3Kind
  27743. * - BABYLON.VertexBuffer.UV4Kind
  27744. * - BABYLON.VertexBuffer.UV5Kind
  27745. * - BABYLON.VertexBuffer.UV6Kind
  27746. * - BABYLON.VertexBuffer.ColorKind
  27747. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27748. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27749. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27750. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27751. */
  27752. Mesh.prototype.getVerticesDataKinds = function () {
  27753. if (!this._geometry) {
  27754. var result = new Array();
  27755. if (this._delayInfo) {
  27756. this._delayInfo.forEach(function (kind, index, array) {
  27757. result.push(kind);
  27758. });
  27759. }
  27760. return result;
  27761. }
  27762. return this._geometry.getVerticesDataKinds();
  27763. };
  27764. /**
  27765. * Returns a positive integer : the total number of indices in this mesh geometry.
  27766. * Returns zero if the mesh has no geometry.
  27767. */
  27768. Mesh.prototype.getTotalIndices = function () {
  27769. if (!this._geometry) {
  27770. return 0;
  27771. }
  27772. return this._geometry.getTotalIndices();
  27773. };
  27774. /**
  27775. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27776. * 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.
  27777. * Returns an empty array if the mesh has no geometry.
  27778. */
  27779. Mesh.prototype.getIndices = function (copyWhenShared) {
  27780. if (!this._geometry) {
  27781. return [];
  27782. }
  27783. return this._geometry.getIndices(copyWhenShared);
  27784. };
  27785. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27786. get: function () {
  27787. return this._masterMesh !== null && this._masterMesh !== undefined;
  27788. },
  27789. enumerable: true,
  27790. configurable: true
  27791. });
  27792. /**
  27793. * Determine if the current mesh is ready to be rendered
  27794. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27795. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27796. * @returns true if all associated assets are ready (material, textures, shaders)
  27797. */
  27798. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27799. if (completeCheck === void 0) { completeCheck = false; }
  27800. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27801. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27802. return false;
  27803. }
  27804. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27805. return false;
  27806. }
  27807. if (!this.subMeshes || this.subMeshes.length === 0) {
  27808. return true;
  27809. }
  27810. if (!completeCheck) {
  27811. return true;
  27812. }
  27813. var engine = this.getEngine();
  27814. var scene = this.getScene();
  27815. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27816. this.computeWorldMatrix();
  27817. var mat = this.material || scene.defaultMaterial;
  27818. if (mat) {
  27819. if (mat.storeEffectOnSubMeshes) {
  27820. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27821. var subMesh = _a[_i];
  27822. var effectiveMaterial = subMesh.getMaterial();
  27823. if (effectiveMaterial) {
  27824. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27825. return false;
  27826. }
  27827. }
  27828. }
  27829. }
  27830. else {
  27831. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27832. return false;
  27833. }
  27834. }
  27835. }
  27836. // Shadows
  27837. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27838. var light = _c[_b];
  27839. var generator = light.getShadowGenerator();
  27840. if (generator) {
  27841. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27842. var subMesh = _e[_d];
  27843. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27844. return false;
  27845. }
  27846. }
  27847. }
  27848. }
  27849. // LOD
  27850. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27851. var lod = _g[_f];
  27852. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27853. return false;
  27854. }
  27855. }
  27856. return true;
  27857. };
  27858. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27859. /**
  27860. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27861. * This property is pertinent only for updatable parametric shapes.
  27862. */
  27863. get: function () {
  27864. return this._areNormalsFrozen;
  27865. },
  27866. enumerable: true,
  27867. configurable: true
  27868. });
  27869. /**
  27870. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27871. * It has no effect at all on other shapes.
  27872. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27873. * Returns the Mesh.
  27874. */
  27875. Mesh.prototype.freezeNormals = function () {
  27876. this._areNormalsFrozen = true;
  27877. return this;
  27878. };
  27879. /**
  27880. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27881. * It has no effect at all on other shapes.
  27882. * It reactivates the mesh normals computation if it was previously frozen.
  27883. * Returns the Mesh.
  27884. */
  27885. Mesh.prototype.unfreezeNormals = function () {
  27886. this._areNormalsFrozen = false;
  27887. return this;
  27888. };
  27889. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27890. /**
  27891. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27892. */
  27893. set: function (count) {
  27894. this._overridenInstanceCount = count;
  27895. },
  27896. enumerable: true,
  27897. configurable: true
  27898. });
  27899. // Methods
  27900. Mesh.prototype._preActivate = function () {
  27901. var sceneRenderId = this.getScene().getRenderId();
  27902. if (this._preActivateId === sceneRenderId) {
  27903. return this;
  27904. }
  27905. this._preActivateId = sceneRenderId;
  27906. this._visibleInstances = null;
  27907. return this;
  27908. };
  27909. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27910. if (this._visibleInstances) {
  27911. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27912. }
  27913. return this;
  27914. };
  27915. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27916. if (!this._visibleInstances) {
  27917. this._visibleInstances = {};
  27918. this._visibleInstances.defaultRenderId = renderId;
  27919. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27920. }
  27921. if (!this._visibleInstances[renderId]) {
  27922. this._visibleInstances[renderId] = new Array();
  27923. }
  27924. this._visibleInstances[renderId].push(instance);
  27925. return this;
  27926. };
  27927. /**
  27928. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27929. * This means the mesh underlying bounding box and sphere are recomputed.
  27930. * Returns the Mesh.
  27931. */
  27932. Mesh.prototype.refreshBoundingInfo = function () {
  27933. return this._refreshBoundingInfo(false);
  27934. };
  27935. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27936. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27937. return this;
  27938. }
  27939. var data = this._getPositionData(applySkeleton);
  27940. if (data) {
  27941. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27942. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27943. }
  27944. if (this.subMeshes) {
  27945. for (var index = 0; index < this.subMeshes.length; index++) {
  27946. this.subMeshes[index].refreshBoundingInfo();
  27947. }
  27948. }
  27949. this._updateBoundingInfo();
  27950. return this;
  27951. };
  27952. Mesh.prototype._getPositionData = function (applySkeleton) {
  27953. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27954. if (data && applySkeleton && this.skeleton) {
  27955. data = BABYLON.Tools.Slice(data);
  27956. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27957. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27958. if (matricesWeightsData && matricesIndicesData) {
  27959. var needExtras = this.numBoneInfluencers > 4;
  27960. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27961. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27962. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27963. var tempVector = BABYLON.Tmp.Vector3[0];
  27964. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27965. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27966. var matWeightIdx = 0;
  27967. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27968. finalMatrix.reset();
  27969. var inf;
  27970. var weight;
  27971. for (inf = 0; inf < 4; inf++) {
  27972. weight = matricesWeightsData[matWeightIdx + inf];
  27973. if (weight <= 0)
  27974. break;
  27975. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27976. finalMatrix.addToSelf(tempMatrix);
  27977. }
  27978. if (needExtras) {
  27979. for (inf = 0; inf < 4; inf++) {
  27980. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27981. if (weight <= 0)
  27982. break;
  27983. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27984. finalMatrix.addToSelf(tempMatrix);
  27985. }
  27986. }
  27987. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27988. tempVector.toArray(data, index);
  27989. }
  27990. }
  27991. }
  27992. return data;
  27993. };
  27994. Mesh.prototype._createGlobalSubMesh = function (force) {
  27995. var totalVertices = this.getTotalVertices();
  27996. if (!totalVertices || !this.getIndices()) {
  27997. return null;
  27998. }
  27999. // Check if we need to recreate the submeshes
  28000. if (this.subMeshes && this.subMeshes.length > 0) {
  28001. var ib = this.getIndices();
  28002. if (!ib) {
  28003. return null;
  28004. }
  28005. var totalIndices = ib.length;
  28006. var needToRecreate = false;
  28007. if (force) {
  28008. needToRecreate = true;
  28009. }
  28010. else {
  28011. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28012. var submesh = _a[_i];
  28013. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28014. needToRecreate = true;
  28015. break;
  28016. }
  28017. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28018. needToRecreate = true;
  28019. break;
  28020. }
  28021. }
  28022. }
  28023. if (!needToRecreate) {
  28024. return this.subMeshes[0];
  28025. }
  28026. }
  28027. this.releaseSubMeshes();
  28028. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28029. };
  28030. Mesh.prototype.subdivide = function (count) {
  28031. if (count < 1) {
  28032. return;
  28033. }
  28034. var totalIndices = this.getTotalIndices();
  28035. var subdivisionSize = (totalIndices / count) | 0;
  28036. var offset = 0;
  28037. // Ensure that subdivisionSize is a multiple of 3
  28038. while (subdivisionSize % 3 !== 0) {
  28039. subdivisionSize++;
  28040. }
  28041. this.releaseSubMeshes();
  28042. for (var index = 0; index < count; index++) {
  28043. if (offset >= totalIndices) {
  28044. break;
  28045. }
  28046. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28047. offset += subdivisionSize;
  28048. }
  28049. this.synchronizeInstances();
  28050. };
  28051. /**
  28052. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28053. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28054. * The `data` are either a numeric array either a Float32Array.
  28055. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28056. * 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).
  28057. * Note that a new underlying VertexBuffer object is created each call.
  28058. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28059. *
  28060. * Possible `kind` values :
  28061. * - BABYLON.VertexBuffer.PositionKind
  28062. * - BABYLON.VertexBuffer.UVKind
  28063. * - BABYLON.VertexBuffer.UV2Kind
  28064. * - BABYLON.VertexBuffer.UV3Kind
  28065. * - BABYLON.VertexBuffer.UV4Kind
  28066. * - BABYLON.VertexBuffer.UV5Kind
  28067. * - BABYLON.VertexBuffer.UV6Kind
  28068. * - BABYLON.VertexBuffer.ColorKind
  28069. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28070. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28071. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28072. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28073. *
  28074. * Returns the Mesh.
  28075. */
  28076. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28077. if (updatable === void 0) { updatable = false; }
  28078. if (!this._geometry) {
  28079. var vertexData = new BABYLON.VertexData();
  28080. vertexData.set(data, kind);
  28081. var scene = this.getScene();
  28082. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28083. }
  28084. else {
  28085. this._geometry.setVerticesData(kind, data, updatable, stride);
  28086. }
  28087. return this;
  28088. };
  28089. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28090. if (updatable === void 0) { updatable = true; }
  28091. var vb = this.getVertexBuffer(kind);
  28092. if (!vb || vb.isUpdatable() === updatable) {
  28093. return;
  28094. }
  28095. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28096. };
  28097. /**
  28098. * Sets the mesh VertexBuffer.
  28099. * Returns the Mesh.
  28100. */
  28101. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28102. if (!this._geometry) {
  28103. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28104. }
  28105. this._geometry.setVerticesBuffer(buffer);
  28106. return this;
  28107. };
  28108. /**
  28109. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28110. * If the mesh has no geometry, it is simply returned as it is.
  28111. * The `data` are either a numeric array either a Float32Array.
  28112. * No new underlying VertexBuffer object is created.
  28113. * 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.
  28114. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28115. *
  28116. * Possible `kind` values :
  28117. * - BABYLON.VertexBuffer.PositionKind
  28118. * - BABYLON.VertexBuffer.UVKind
  28119. * - BABYLON.VertexBuffer.UV2Kind
  28120. * - BABYLON.VertexBuffer.UV3Kind
  28121. * - BABYLON.VertexBuffer.UV4Kind
  28122. * - BABYLON.VertexBuffer.UV5Kind
  28123. * - BABYLON.VertexBuffer.UV6Kind
  28124. * - BABYLON.VertexBuffer.ColorKind
  28125. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28126. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28127. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28128. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28129. *
  28130. * Returns the Mesh.
  28131. */
  28132. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28133. if (!this._geometry) {
  28134. return this;
  28135. }
  28136. if (!makeItUnique) {
  28137. this._geometry.updateVerticesData(kind, data, updateExtends);
  28138. }
  28139. else {
  28140. this.makeGeometryUnique();
  28141. this.updateVerticesData(kind, data, updateExtends, false);
  28142. }
  28143. return this;
  28144. };
  28145. /**
  28146. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28147. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28148. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28149. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28150. * Returns the Mesh.
  28151. */
  28152. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28153. if (computeNormals === void 0) { computeNormals = true; }
  28154. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28155. if (!positions) {
  28156. return this;
  28157. }
  28158. positionFunction(positions);
  28159. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28160. if (computeNormals) {
  28161. var indices = this.getIndices();
  28162. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28163. if (!normals) {
  28164. return this;
  28165. }
  28166. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28167. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28168. }
  28169. return this;
  28170. };
  28171. /**
  28172. * Creates a un-shared specific occurence of the geometry for the mesh.
  28173. * Returns the Mesh.
  28174. */
  28175. Mesh.prototype.makeGeometryUnique = function () {
  28176. if (!this._geometry) {
  28177. return this;
  28178. }
  28179. var oldGeometry = this._geometry;
  28180. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28181. oldGeometry.releaseForMesh(this, true);
  28182. geometry.applyToMesh(this);
  28183. return this;
  28184. };
  28185. /**
  28186. * Sets the mesh indices.
  28187. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28188. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28189. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28190. * This method creates a new index buffer each call.
  28191. * Returns the Mesh.
  28192. */
  28193. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28194. if (totalVertices === void 0) { totalVertices = null; }
  28195. if (updatable === void 0) { updatable = false; }
  28196. if (!this._geometry) {
  28197. var vertexData = new BABYLON.VertexData();
  28198. vertexData.indices = indices;
  28199. var scene = this.getScene();
  28200. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28201. }
  28202. else {
  28203. this._geometry.setIndices(indices, totalVertices, updatable);
  28204. }
  28205. return this;
  28206. };
  28207. /**
  28208. * Update the current index buffer
  28209. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28210. * Returns the Mesh.
  28211. */
  28212. Mesh.prototype.updateIndices = function (indices, offset) {
  28213. if (!this._geometry) {
  28214. return this;
  28215. }
  28216. this._geometry.updateIndices(indices, offset);
  28217. return this;
  28218. };
  28219. /**
  28220. * Invert the geometry to move from a right handed system to a left handed one.
  28221. * Returns the Mesh.
  28222. */
  28223. Mesh.prototype.toLeftHanded = function () {
  28224. if (!this._geometry) {
  28225. return this;
  28226. }
  28227. this._geometry.toLeftHanded();
  28228. return this;
  28229. };
  28230. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28231. if (!this._geometry) {
  28232. return this;
  28233. }
  28234. var engine = this.getScene().getEngine();
  28235. // Wireframe
  28236. var indexToBind;
  28237. if (this._unIndexed) {
  28238. indexToBind = null;
  28239. }
  28240. else {
  28241. switch (fillMode) {
  28242. case BABYLON.Material.PointFillMode:
  28243. indexToBind = null;
  28244. break;
  28245. case BABYLON.Material.WireFrameFillMode:
  28246. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28247. break;
  28248. default:
  28249. case BABYLON.Material.TriangleFillMode:
  28250. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28251. break;
  28252. }
  28253. }
  28254. // VBOs
  28255. this._geometry._bind(effect, indexToBind);
  28256. return this;
  28257. };
  28258. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28259. if (alternate === void 0) { alternate = false; }
  28260. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28261. return this;
  28262. }
  28263. this.onBeforeDrawObservable.notifyObservers(this);
  28264. var scene = this.getScene();
  28265. var engine = scene.getEngine();
  28266. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28267. // or triangles as points
  28268. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28269. }
  28270. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28271. // Triangles as wireframe
  28272. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28273. }
  28274. else {
  28275. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28276. }
  28277. if (scene._isAlternateRenderingEnabled && !alternate) {
  28278. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28279. if (!effect || !scene.activeCamera) {
  28280. return this;
  28281. }
  28282. scene._switchToAlternateCameraConfiguration(true);
  28283. this._effectiveMaterial.bindView(effect);
  28284. this._effectiveMaterial.bindViewProjection(effect);
  28285. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28286. this._draw(subMesh, fillMode, instancesCount, true);
  28287. engine.setViewport(scene.activeCamera.viewport);
  28288. scene._switchToAlternateCameraConfiguration(false);
  28289. this._effectiveMaterial.bindView(effect);
  28290. this._effectiveMaterial.bindViewProjection(effect);
  28291. }
  28292. return this;
  28293. };
  28294. /**
  28295. * Registers for this mesh a javascript function called just before the rendering process.
  28296. * This function is passed the current mesh.
  28297. * Return the Mesh.
  28298. */
  28299. Mesh.prototype.registerBeforeRender = function (func) {
  28300. this.onBeforeRenderObservable.add(func);
  28301. return this;
  28302. };
  28303. /**
  28304. * Disposes a previously registered javascript function called before the rendering.
  28305. * This function is passed the current mesh.
  28306. * Returns the Mesh.
  28307. */
  28308. Mesh.prototype.unregisterBeforeRender = function (func) {
  28309. this.onBeforeRenderObservable.removeCallback(func);
  28310. return this;
  28311. };
  28312. /**
  28313. * Registers for this mesh a javascript function called just after the rendering is complete.
  28314. * This function is passed the current mesh.
  28315. * Returns the Mesh.
  28316. */
  28317. Mesh.prototype.registerAfterRender = function (func) {
  28318. this.onAfterRenderObservable.add(func);
  28319. return this;
  28320. };
  28321. /**
  28322. * Disposes a previously registered javascript function called after the rendering.
  28323. * This function is passed the current mesh.
  28324. * Return the Mesh.
  28325. */
  28326. Mesh.prototype.unregisterAfterRender = function (func) {
  28327. this.onAfterRenderObservable.removeCallback(func);
  28328. return this;
  28329. };
  28330. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28331. var scene = this.getScene();
  28332. this._batchCache.mustReturn = false;
  28333. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28334. this._batchCache.visibleInstances[subMeshId] = null;
  28335. if (this._visibleInstances) {
  28336. var currentRenderId = scene.getRenderId();
  28337. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28338. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28339. var selfRenderId = this._renderId;
  28340. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28341. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28342. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28343. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28344. }
  28345. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28346. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28347. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28348. this._batchCache.mustReturn = true;
  28349. return this._batchCache;
  28350. }
  28351. if (currentRenderId !== selfRenderId) {
  28352. this._batchCache.renderSelf[subMeshId] = false;
  28353. }
  28354. }
  28355. this._renderIdForInstances[subMeshId] = currentRenderId;
  28356. }
  28357. return this._batchCache;
  28358. };
  28359. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28360. var visibleInstances = batch.visibleInstances[subMesh._id];
  28361. if (!visibleInstances) {
  28362. return this;
  28363. }
  28364. var matricesCount = visibleInstances.length + 1;
  28365. var bufferSize = matricesCount * 16 * 4;
  28366. var currentInstancesBufferSize = this._instancesBufferSize;
  28367. var instancesBuffer = this._instancesBuffer;
  28368. while (this._instancesBufferSize < bufferSize) {
  28369. this._instancesBufferSize *= 2;
  28370. }
  28371. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28372. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28373. }
  28374. var offset = 0;
  28375. var instancesCount = 0;
  28376. var world = this.getWorldMatrix();
  28377. if (batch.renderSelf[subMesh._id]) {
  28378. world.copyToArray(this._instancesData, offset);
  28379. offset += 16;
  28380. instancesCount++;
  28381. }
  28382. if (visibleInstances) {
  28383. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28384. var instance = visibleInstances[instanceIndex];
  28385. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28386. offset += 16;
  28387. instancesCount++;
  28388. }
  28389. }
  28390. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28391. if (instancesBuffer) {
  28392. instancesBuffer.dispose();
  28393. }
  28394. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28395. this._instancesBuffer = instancesBuffer;
  28396. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28397. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28398. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28399. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28400. }
  28401. else {
  28402. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28403. }
  28404. this._bind(subMesh, effect, fillMode);
  28405. this._draw(subMesh, fillMode, instancesCount);
  28406. engine.unbindInstanceAttributes();
  28407. return this;
  28408. };
  28409. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28410. var scene = this.getScene();
  28411. var engine = scene.getEngine();
  28412. if (hardwareInstancedRendering) {
  28413. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28414. }
  28415. else {
  28416. if (batch.renderSelf[subMesh._id]) {
  28417. // Draw
  28418. if (onBeforeDraw) {
  28419. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28420. }
  28421. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28422. }
  28423. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28424. if (visibleInstancesForSubMesh) {
  28425. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28426. var instance = visibleInstancesForSubMesh[instanceIndex];
  28427. // World
  28428. var world = instance.getWorldMatrix();
  28429. if (onBeforeDraw) {
  28430. onBeforeDraw(true, world, effectiveMaterial);
  28431. }
  28432. // Draw
  28433. this._draw(subMesh, fillMode);
  28434. }
  28435. }
  28436. }
  28437. return this;
  28438. };
  28439. /**
  28440. * Triggers the draw call for the mesh.
  28441. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28442. * Returns the Mesh.
  28443. */
  28444. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28445. this.checkOcclusionQuery();
  28446. if (this._isOccluded) {
  28447. return this;
  28448. }
  28449. var scene = this.getScene();
  28450. // Managing instances
  28451. var batch = this._getInstancesRenderList(subMesh._id);
  28452. if (batch.mustReturn) {
  28453. return this;
  28454. }
  28455. // Checking geometry state
  28456. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28457. return this;
  28458. }
  28459. this.onBeforeRenderObservable.notifyObservers(this);
  28460. var engine = scene.getEngine();
  28461. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28462. // Material
  28463. var material = subMesh.getMaterial();
  28464. if (!material) {
  28465. return this;
  28466. }
  28467. this._effectiveMaterial = material;
  28468. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28469. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28470. return this;
  28471. }
  28472. }
  28473. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28474. return this;
  28475. }
  28476. // Alpha mode
  28477. if (enableAlphaMode) {
  28478. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28479. }
  28480. // Outline - step 1
  28481. var savedDepthWrite = engine.getDepthWrite();
  28482. if (this.renderOutline) {
  28483. engine.setDepthWrite(false);
  28484. scene.getOutlineRenderer().render(subMesh, batch);
  28485. engine.setDepthWrite(savedDepthWrite);
  28486. }
  28487. var effect;
  28488. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28489. effect = subMesh.effect;
  28490. }
  28491. else {
  28492. effect = this._effectiveMaterial.getEffect();
  28493. }
  28494. if (!effect) {
  28495. return this;
  28496. }
  28497. var sideOrientation = this.overrideMaterialSideOrientation;
  28498. if (sideOrientation == null) {
  28499. sideOrientation = this._effectiveMaterial.sideOrientation;
  28500. if (this._getWorldMatrixDeterminant() < 0) {
  28501. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28502. }
  28503. }
  28504. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28505. if (this._effectiveMaterial.forceDepthWrite) {
  28506. engine.setDepthWrite(true);
  28507. }
  28508. // Bind
  28509. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28510. if (!hardwareInstancedRendering) {
  28511. this._bind(subMesh, effect, fillMode);
  28512. }
  28513. var world = this.getWorldMatrix();
  28514. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28515. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28516. }
  28517. else {
  28518. this._effectiveMaterial.bind(world, this);
  28519. }
  28520. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28521. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28522. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28523. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28524. }
  28525. // Draw
  28526. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28527. // Unbind
  28528. this._effectiveMaterial.unbind();
  28529. // Outline - step 2
  28530. if (this.renderOutline && savedDepthWrite) {
  28531. engine.setDepthWrite(true);
  28532. engine.setColorWrite(false);
  28533. scene.getOutlineRenderer().render(subMesh, batch);
  28534. engine.setColorWrite(true);
  28535. }
  28536. // Overlay
  28537. if (this.renderOverlay) {
  28538. var currentMode = engine.getAlphaMode();
  28539. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28540. scene.getOutlineRenderer().render(subMesh, batch, true);
  28541. engine.setAlphaMode(currentMode);
  28542. }
  28543. this.onAfterRenderObservable.notifyObservers(this);
  28544. return this;
  28545. };
  28546. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28547. if (isInstance && effectiveMaterial) {
  28548. effectiveMaterial.bindOnlyWorldMatrix(world);
  28549. }
  28550. };
  28551. /**
  28552. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28553. */
  28554. Mesh.prototype.getEmittedParticleSystems = function () {
  28555. var results = new Array();
  28556. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28557. var particleSystem = this.getScene().particleSystems[index];
  28558. if (particleSystem.emitter === this) {
  28559. results.push(particleSystem);
  28560. }
  28561. }
  28562. return results;
  28563. };
  28564. /**
  28565. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28566. */
  28567. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28568. var results = new Array();
  28569. var descendants = this.getDescendants();
  28570. descendants.push(this);
  28571. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28572. var particleSystem = this.getScene().particleSystems[index];
  28573. var emitter = particleSystem.emitter;
  28574. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28575. results.push(particleSystem);
  28576. }
  28577. }
  28578. return results;
  28579. };
  28580. Mesh.prototype._checkDelayState = function () {
  28581. var scene = this.getScene();
  28582. if (this._geometry) {
  28583. this._geometry.load(scene);
  28584. }
  28585. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28586. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28587. this._queueLoad(scene);
  28588. }
  28589. return this;
  28590. };
  28591. Mesh.prototype._queueLoad = function (scene) {
  28592. var _this = this;
  28593. scene._addPendingData(this);
  28594. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28595. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28596. if (data instanceof ArrayBuffer) {
  28597. _this._delayLoadingFunction(data, _this);
  28598. }
  28599. else {
  28600. _this._delayLoadingFunction(JSON.parse(data), _this);
  28601. }
  28602. _this.instances.forEach(function (instance) {
  28603. instance._syncSubMeshes();
  28604. });
  28605. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28606. scene._removePendingData(_this);
  28607. }, function () { }, scene.database, getBinaryData);
  28608. return this;
  28609. };
  28610. /**
  28611. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28612. */
  28613. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28614. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28615. return false;
  28616. }
  28617. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28618. return false;
  28619. }
  28620. this._checkDelayState();
  28621. return true;
  28622. };
  28623. /**
  28624. * Sets the mesh material by the material or multiMaterial `id` property.
  28625. * The material `id` is a string identifying the material or the multiMaterial.
  28626. * This method returns the Mesh.
  28627. */
  28628. Mesh.prototype.setMaterialByID = function (id) {
  28629. var materials = this.getScene().materials;
  28630. var index;
  28631. for (index = materials.length - 1; index > -1; index--) {
  28632. if (materials[index].id === id) {
  28633. this.material = materials[index];
  28634. return this;
  28635. }
  28636. }
  28637. // Multi
  28638. var multiMaterials = this.getScene().multiMaterials;
  28639. for (index = multiMaterials.length - 1; index > -1; index--) {
  28640. if (multiMaterials[index].id === id) {
  28641. this.material = multiMaterials[index];
  28642. return this;
  28643. }
  28644. }
  28645. return this;
  28646. };
  28647. /**
  28648. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28649. */
  28650. Mesh.prototype.getAnimatables = function () {
  28651. var results = new Array();
  28652. if (this.material) {
  28653. results.push(this.material);
  28654. }
  28655. if (this.skeleton) {
  28656. results.push(this.skeleton);
  28657. }
  28658. return results;
  28659. };
  28660. /**
  28661. * Modifies the mesh geometry according to the passed transformation matrix.
  28662. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28663. * The mesh normals are modified accordingly the same transformation.
  28664. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28665. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28666. * Returns the Mesh.
  28667. */
  28668. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28669. // Position
  28670. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28671. return this;
  28672. }
  28673. var submeshes = this.subMeshes.splice(0);
  28674. this._resetPointsArrayCache();
  28675. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28676. var temp = new Array();
  28677. var index;
  28678. for (index = 0; index < data.length; index += 3) {
  28679. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28680. }
  28681. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28682. // Normals
  28683. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28684. return this;
  28685. }
  28686. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28687. temp = [];
  28688. for (index = 0; index < data.length; index += 3) {
  28689. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28690. }
  28691. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28692. // flip faces?
  28693. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28694. this.flipFaces();
  28695. }
  28696. // Restore submeshes
  28697. this.releaseSubMeshes();
  28698. this.subMeshes = submeshes;
  28699. return this;
  28700. };
  28701. /**
  28702. * Modifies the mesh geometry according to its own current World Matrix.
  28703. * The mesh World Matrix is then reset.
  28704. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28705. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28706. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28707. * Returns the Mesh.
  28708. */
  28709. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28710. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28711. this.scaling.copyFromFloats(1, 1, 1);
  28712. this.position.copyFromFloats(0, 0, 0);
  28713. this.rotation.copyFromFloats(0, 0, 0);
  28714. //only if quaternion is already set
  28715. if (this.rotationQuaternion) {
  28716. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28717. }
  28718. this._worldMatrix = BABYLON.Matrix.Identity();
  28719. return this;
  28720. };
  28721. Object.defineProperty(Mesh.prototype, "_positions", {
  28722. // Cache
  28723. get: function () {
  28724. if (this._geometry) {
  28725. return this._geometry._positions;
  28726. }
  28727. return null;
  28728. },
  28729. enumerable: true,
  28730. configurable: true
  28731. });
  28732. Mesh.prototype._resetPointsArrayCache = function () {
  28733. if (this._geometry) {
  28734. this._geometry._resetPointsArrayCache();
  28735. }
  28736. return this;
  28737. };
  28738. Mesh.prototype._generatePointsArray = function () {
  28739. if (this._geometry) {
  28740. return this._geometry._generatePointsArray();
  28741. }
  28742. return false;
  28743. };
  28744. /**
  28745. * Returns a new Mesh object generated from the current mesh properties.
  28746. * This method must not get confused with createInstance().
  28747. * The parameter `name` is a string, the name given to the new mesh.
  28748. * The optional parameter `newParent` can be any Node object (default `null`).
  28749. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28750. * 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.
  28751. */
  28752. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28753. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28754. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28755. };
  28756. /**
  28757. * Releases resources associated with this mesh.
  28758. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28759. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28760. */
  28761. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28762. var _this = this;
  28763. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28764. this.morphTargetManager = null;
  28765. if (this._geometry) {
  28766. this._geometry.releaseForMesh(this, true);
  28767. }
  28768. // Sources
  28769. var meshes = this.getScene().meshes;
  28770. meshes.forEach(function (abstractMesh) {
  28771. var mesh = abstractMesh;
  28772. if (mesh._source && mesh._source === _this) {
  28773. mesh._source = null;
  28774. }
  28775. });
  28776. this._source = null;
  28777. // Instances
  28778. if (this._instancesBuffer) {
  28779. this._instancesBuffer.dispose();
  28780. this._instancesBuffer = null;
  28781. }
  28782. while (this.instances.length) {
  28783. this.instances[0].dispose();
  28784. }
  28785. // Effect layers.
  28786. var effectLayers = this.getScene().effectLayers;
  28787. for (var i = 0; i < effectLayers.length; i++) {
  28788. var effectLayer = effectLayers[i];
  28789. if (effectLayer) {
  28790. effectLayer._disposeMesh(this);
  28791. }
  28792. }
  28793. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28794. };
  28795. /**
  28796. * Modifies the mesh geometry according to a displacement map.
  28797. * 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.
  28798. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28799. * This method returns nothing.
  28800. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28801. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28802. * 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.
  28803. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28804. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28805. *
  28806. * Returns the Mesh.
  28807. */
  28808. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28809. var _this = this;
  28810. var scene = this.getScene();
  28811. var onload = function (img) {
  28812. // Getting height map data
  28813. var canvas = document.createElement("canvas");
  28814. var context = canvas.getContext("2d");
  28815. var heightMapWidth = img.width;
  28816. var heightMapHeight = img.height;
  28817. canvas.width = heightMapWidth;
  28818. canvas.height = heightMapHeight;
  28819. context.drawImage(img, 0, 0);
  28820. // Create VertexData from map data
  28821. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28822. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28823. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28824. //execute success callback, if set
  28825. if (onSuccess) {
  28826. onSuccess(_this);
  28827. }
  28828. };
  28829. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28830. return this;
  28831. };
  28832. /**
  28833. * Modifies the mesh geometry according to a displacementMap buffer.
  28834. * 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.
  28835. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28836. * This method returns nothing.
  28837. * 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.
  28838. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28839. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28840. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28841. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28842. *
  28843. * Returns the Mesh.
  28844. */
  28845. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28846. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28847. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28848. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28849. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28850. return this;
  28851. }
  28852. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28853. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28854. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28855. var position = BABYLON.Vector3.Zero();
  28856. var normal = BABYLON.Vector3.Zero();
  28857. var uv = BABYLON.Vector2.Zero();
  28858. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28859. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28860. for (var index = 0; index < positions.length; index += 3) {
  28861. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28862. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28863. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28864. // Compute height
  28865. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28866. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28867. var pos = (u + v * heightMapWidth) * 4;
  28868. var r = buffer[pos] / 255.0;
  28869. var g = buffer[pos + 1] / 255.0;
  28870. var b = buffer[pos + 2] / 255.0;
  28871. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28872. normal.normalize();
  28873. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28874. position = position.add(normal);
  28875. position.toArray(positions, index);
  28876. }
  28877. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28878. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28879. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28880. return this;
  28881. };
  28882. /**
  28883. * Modify the mesh to get a flat shading rendering.
  28884. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28885. * This method returns the Mesh.
  28886. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28887. */
  28888. Mesh.prototype.convertToFlatShadedMesh = function () {
  28889. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28890. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28891. var kinds = this.getVerticesDataKinds();
  28892. var vbs = {};
  28893. var data = {};
  28894. var newdata = {};
  28895. var updatableNormals = false;
  28896. var kindIndex;
  28897. var kind;
  28898. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28899. kind = kinds[kindIndex];
  28900. var vertexBuffer = this.getVertexBuffer(kind);
  28901. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28902. updatableNormals = vertexBuffer.isUpdatable();
  28903. kinds.splice(kindIndex, 1);
  28904. kindIndex--;
  28905. continue;
  28906. }
  28907. vbs[kind] = vertexBuffer;
  28908. data[kind] = vbs[kind].getData();
  28909. newdata[kind] = [];
  28910. }
  28911. // Save previous submeshes
  28912. var previousSubmeshes = this.subMeshes.slice(0);
  28913. var indices = this.getIndices();
  28914. var totalIndices = this.getTotalIndices();
  28915. // Generating unique vertices per face
  28916. var index;
  28917. for (index = 0; index < totalIndices; index++) {
  28918. var vertexIndex = indices[index];
  28919. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28920. kind = kinds[kindIndex];
  28921. var stride = vbs[kind].getStrideSize();
  28922. for (var offset = 0; offset < stride; offset++) {
  28923. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28924. }
  28925. }
  28926. }
  28927. // Updating faces & normal
  28928. var normals = [];
  28929. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28930. for (index = 0; index < totalIndices; index += 3) {
  28931. indices[index] = index;
  28932. indices[index + 1] = index + 1;
  28933. indices[index + 2] = index + 2;
  28934. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28935. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28936. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28937. var p1p2 = p1.subtract(p2);
  28938. var p3p2 = p3.subtract(p2);
  28939. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28940. // Store same normals for every vertex
  28941. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28942. normals.push(normal.x);
  28943. normals.push(normal.y);
  28944. normals.push(normal.z);
  28945. }
  28946. }
  28947. this.setIndices(indices);
  28948. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28949. // Updating vertex buffers
  28950. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28951. kind = kinds[kindIndex];
  28952. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28953. }
  28954. // Updating submeshes
  28955. this.releaseSubMeshes();
  28956. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28957. var previousOne = previousSubmeshes[submeshIndex];
  28958. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28959. }
  28960. this.synchronizeInstances();
  28961. return this;
  28962. };
  28963. /**
  28964. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28965. * In other words, more vertices, no more indices and a single bigger VBO.
  28966. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28967. * Returns the Mesh.
  28968. */
  28969. Mesh.prototype.convertToUnIndexedMesh = function () {
  28970. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28971. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28972. var kinds = this.getVerticesDataKinds();
  28973. var vbs = {};
  28974. var data = {};
  28975. var newdata = {};
  28976. var kindIndex;
  28977. var kind;
  28978. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28979. kind = kinds[kindIndex];
  28980. var vertexBuffer = this.getVertexBuffer(kind);
  28981. vbs[kind] = vertexBuffer;
  28982. data[kind] = vbs[kind].getData();
  28983. newdata[kind] = [];
  28984. }
  28985. // Save previous submeshes
  28986. var previousSubmeshes = this.subMeshes.slice(0);
  28987. var indices = this.getIndices();
  28988. var totalIndices = this.getTotalIndices();
  28989. // Generating unique vertices per face
  28990. var index;
  28991. for (index = 0; index < totalIndices; index++) {
  28992. var vertexIndex = indices[index];
  28993. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28994. kind = kinds[kindIndex];
  28995. var stride = vbs[kind].getStrideSize();
  28996. for (var offset = 0; offset < stride; offset++) {
  28997. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28998. }
  28999. }
  29000. }
  29001. // Updating indices
  29002. for (index = 0; index < totalIndices; index += 3) {
  29003. indices[index] = index;
  29004. indices[index + 1] = index + 1;
  29005. indices[index + 2] = index + 2;
  29006. }
  29007. this.setIndices(indices);
  29008. // Updating vertex buffers
  29009. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29010. kind = kinds[kindIndex];
  29011. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29012. }
  29013. // Updating submeshes
  29014. this.releaseSubMeshes();
  29015. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29016. var previousOne = previousSubmeshes[submeshIndex];
  29017. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29018. }
  29019. this._unIndexed = true;
  29020. this.synchronizeInstances();
  29021. return this;
  29022. };
  29023. /**
  29024. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29025. * This method returns the Mesh.
  29026. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29027. */
  29028. Mesh.prototype.flipFaces = function (flipNormals) {
  29029. if (flipNormals === void 0) { flipNormals = false; }
  29030. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29031. var i;
  29032. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29033. for (i = 0; i < vertex_data.normals.length; i++) {
  29034. vertex_data.normals[i] *= -1;
  29035. }
  29036. }
  29037. if (vertex_data.indices) {
  29038. var temp;
  29039. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29040. // reassign indices
  29041. temp = vertex_data.indices[i + 1];
  29042. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29043. vertex_data.indices[i + 2] = temp;
  29044. }
  29045. }
  29046. vertex_data.applyToMesh(this);
  29047. return this;
  29048. };
  29049. // Instances
  29050. /**
  29051. * Creates a new InstancedMesh object from the mesh model.
  29052. * An instance shares the same properties and the same material than its model.
  29053. * Only these properties of each instance can then be set individually :
  29054. * - position
  29055. * - rotation
  29056. * - rotationQuaternion
  29057. * - setPivotMatrix
  29058. * - scaling
  29059. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29060. * Warning : this method is not supported for Line mesh and LineSystem
  29061. */
  29062. Mesh.prototype.createInstance = function (name) {
  29063. return new BABYLON.InstancedMesh(name, this);
  29064. };
  29065. /**
  29066. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29067. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29068. * This method returns the Mesh.
  29069. */
  29070. Mesh.prototype.synchronizeInstances = function () {
  29071. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29072. var instance = this.instances[instanceIndex];
  29073. instance._syncSubMeshes();
  29074. }
  29075. return this;
  29076. };
  29077. /**
  29078. * Simplify the mesh according to the given array of settings.
  29079. * Function will return immediately and will simplify async. It returns the Mesh.
  29080. * @param settings a collection of simplification settings.
  29081. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29082. * @param type the type of simplification to run.
  29083. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29084. */
  29085. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29086. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29087. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29088. this.getScene().simplificationQueue.addTask({
  29089. settings: settings,
  29090. parallelProcessing: parallelProcessing,
  29091. mesh: this,
  29092. simplificationType: simplificationType,
  29093. successCallback: successCallback
  29094. });
  29095. return this;
  29096. };
  29097. /**
  29098. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29099. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29100. * This should be used together with the simplification to avoid disappearing triangles.
  29101. * Returns the Mesh.
  29102. * @param successCallback an optional success callback to be called after the optimization finished.
  29103. */
  29104. Mesh.prototype.optimizeIndices = function (successCallback) {
  29105. var _this = this;
  29106. var indices = this.getIndices();
  29107. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29108. if (!positions || !indices) {
  29109. return this;
  29110. }
  29111. var vectorPositions = new Array();
  29112. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29113. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29114. }
  29115. var dupes = new Array();
  29116. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29117. var realPos = vectorPositions.length - 1 - iteration;
  29118. var testedPosition = vectorPositions[realPos];
  29119. for (var j = 0; j < realPos; ++j) {
  29120. var againstPosition = vectorPositions[j];
  29121. if (testedPosition.equals(againstPosition)) {
  29122. dupes[realPos] = j;
  29123. break;
  29124. }
  29125. }
  29126. }, function () {
  29127. for (var i = 0; i < indices.length; ++i) {
  29128. indices[i] = dupes[indices[i]] || indices[i];
  29129. }
  29130. //indices are now reordered
  29131. var originalSubMeshes = _this.subMeshes.slice(0);
  29132. _this.setIndices(indices);
  29133. _this.subMeshes = originalSubMeshes;
  29134. if (successCallback) {
  29135. successCallback(_this);
  29136. }
  29137. });
  29138. return this;
  29139. };
  29140. Mesh.prototype.serialize = function (serializationObject) {
  29141. serializationObject.name = this.name;
  29142. serializationObject.id = this.id;
  29143. serializationObject.type = this.getClassName();
  29144. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29145. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29146. }
  29147. serializationObject.position = this.position.asArray();
  29148. if (this.rotationQuaternion) {
  29149. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29150. }
  29151. else if (this.rotation) {
  29152. serializationObject.rotation = this.rotation.asArray();
  29153. }
  29154. serializationObject.scaling = this.scaling.asArray();
  29155. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29156. serializationObject.isEnabled = this.isEnabled(false);
  29157. serializationObject.isVisible = this.isVisible;
  29158. serializationObject.infiniteDistance = this.infiniteDistance;
  29159. serializationObject.pickable = this.isPickable;
  29160. serializationObject.receiveShadows = this.receiveShadows;
  29161. serializationObject.billboardMode = this.billboardMode;
  29162. serializationObject.visibility = this.visibility;
  29163. serializationObject.checkCollisions = this.checkCollisions;
  29164. serializationObject.isBlocker = this.isBlocker;
  29165. // Parent
  29166. if (this.parent) {
  29167. serializationObject.parentId = this.parent.id;
  29168. }
  29169. // Geometry
  29170. serializationObject.isUnIndexed = this.isUnIndexed;
  29171. var geometry = this._geometry;
  29172. if (geometry) {
  29173. var geometryId = geometry.id;
  29174. serializationObject.geometryId = geometryId;
  29175. // SubMeshes
  29176. serializationObject.subMeshes = [];
  29177. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29178. var subMesh = this.subMeshes[subIndex];
  29179. serializationObject.subMeshes.push({
  29180. materialIndex: subMesh.materialIndex,
  29181. verticesStart: subMesh.verticesStart,
  29182. verticesCount: subMesh.verticesCount,
  29183. indexStart: subMesh.indexStart,
  29184. indexCount: subMesh.indexCount
  29185. });
  29186. }
  29187. }
  29188. // Material
  29189. if (this.material) {
  29190. serializationObject.materialId = this.material.id;
  29191. }
  29192. else {
  29193. this.material = null;
  29194. }
  29195. // Morph targets
  29196. if (this.morphTargetManager) {
  29197. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29198. }
  29199. // Skeleton
  29200. if (this.skeleton) {
  29201. serializationObject.skeletonId = this.skeleton.id;
  29202. }
  29203. // Physics
  29204. //TODO implement correct serialization for physics impostors.
  29205. var impostor = this.getPhysicsImpostor();
  29206. if (impostor) {
  29207. serializationObject.physicsMass = impostor.getParam("mass");
  29208. serializationObject.physicsFriction = impostor.getParam("friction");
  29209. serializationObject.physicsRestitution = impostor.getParam("mass");
  29210. serializationObject.physicsImpostor = impostor.type;
  29211. }
  29212. // Metadata
  29213. if (this.metadata) {
  29214. serializationObject.metadata = this.metadata;
  29215. }
  29216. // Instances
  29217. serializationObject.instances = [];
  29218. for (var index = 0; index < this.instances.length; index++) {
  29219. var instance = this.instances[index];
  29220. var serializationInstance = {
  29221. name: instance.name,
  29222. id: instance.id,
  29223. position: instance.position.asArray(),
  29224. scaling: instance.scaling.asArray()
  29225. };
  29226. if (instance.rotationQuaternion) {
  29227. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29228. }
  29229. else if (instance.rotation) {
  29230. serializationInstance.rotation = instance.rotation.asArray();
  29231. }
  29232. serializationObject.instances.push(serializationInstance);
  29233. // Animations
  29234. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29235. serializationInstance.ranges = instance.serializeAnimationRanges();
  29236. }
  29237. //
  29238. // Animations
  29239. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29240. serializationObject.ranges = this.serializeAnimationRanges();
  29241. // Layer mask
  29242. serializationObject.layerMask = this.layerMask;
  29243. // Alpha
  29244. serializationObject.alphaIndex = this.alphaIndex;
  29245. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29246. // Overlay
  29247. serializationObject.overlayAlpha = this.overlayAlpha;
  29248. serializationObject.overlayColor = this.overlayColor.asArray();
  29249. serializationObject.renderOverlay = this.renderOverlay;
  29250. // Fog
  29251. serializationObject.applyFog = this.applyFog;
  29252. // Action Manager
  29253. if (this.actionManager) {
  29254. serializationObject.actions = this.actionManager.serialize(this.name);
  29255. }
  29256. };
  29257. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29258. if (!this.geometry) {
  29259. return;
  29260. }
  29261. this._markSubMeshesAsAttributesDirty();
  29262. var morphTargetManager = this._morphTargetManager;
  29263. if (morphTargetManager && morphTargetManager.vertexCount) {
  29264. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29265. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29266. this.morphTargetManager = null;
  29267. return;
  29268. }
  29269. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29270. var morphTarget = morphTargetManager.getActiveTarget(index);
  29271. var positions = morphTarget.getPositions();
  29272. if (!positions) {
  29273. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29274. return;
  29275. }
  29276. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29277. var normals = morphTarget.getNormals();
  29278. if (normals) {
  29279. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29280. }
  29281. var tangents = morphTarget.getTangents();
  29282. if (tangents) {
  29283. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29284. }
  29285. }
  29286. }
  29287. else {
  29288. var index = 0;
  29289. // Positions
  29290. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29291. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29292. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29293. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29294. }
  29295. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29296. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29297. }
  29298. index++;
  29299. }
  29300. }
  29301. };
  29302. // Statics
  29303. /**
  29304. * Returns a new Mesh object parsed from the source provided.
  29305. * The parameter `parsedMesh` is the source.
  29306. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29307. */
  29308. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29309. var mesh;
  29310. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29311. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29312. }
  29313. else {
  29314. mesh = new Mesh(parsedMesh.name, scene);
  29315. }
  29316. mesh.id = parsedMesh.id;
  29317. if (BABYLON.Tags) {
  29318. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29319. }
  29320. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29321. if (parsedMesh.metadata !== undefined) {
  29322. mesh.metadata = parsedMesh.metadata;
  29323. }
  29324. if (parsedMesh.rotationQuaternion) {
  29325. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29326. }
  29327. else if (parsedMesh.rotation) {
  29328. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29329. }
  29330. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29331. if (parsedMesh.localMatrix) {
  29332. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29333. }
  29334. else if (parsedMesh.pivotMatrix) {
  29335. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29336. }
  29337. mesh.setEnabled(parsedMesh.isEnabled);
  29338. mesh.isVisible = parsedMesh.isVisible;
  29339. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29340. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29341. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29342. if (parsedMesh.applyFog !== undefined) {
  29343. mesh.applyFog = parsedMesh.applyFog;
  29344. }
  29345. if (parsedMesh.pickable !== undefined) {
  29346. mesh.isPickable = parsedMesh.pickable;
  29347. }
  29348. if (parsedMesh.alphaIndex !== undefined) {
  29349. mesh.alphaIndex = parsedMesh.alphaIndex;
  29350. }
  29351. mesh.receiveShadows = parsedMesh.receiveShadows;
  29352. mesh.billboardMode = parsedMesh.billboardMode;
  29353. if (parsedMesh.visibility !== undefined) {
  29354. mesh.visibility = parsedMesh.visibility;
  29355. }
  29356. mesh.checkCollisions = parsedMesh.checkCollisions;
  29357. if (parsedMesh.isBlocker !== undefined) {
  29358. mesh.isBlocker = parsedMesh.isBlocker;
  29359. }
  29360. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29361. // freezeWorldMatrix
  29362. if (parsedMesh.freezeWorldMatrix) {
  29363. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29364. }
  29365. // Parent
  29366. if (parsedMesh.parentId) {
  29367. mesh._waitingParentId = parsedMesh.parentId;
  29368. }
  29369. // Actions
  29370. if (parsedMesh.actions !== undefined) {
  29371. mesh._waitingActions = parsedMesh.actions;
  29372. }
  29373. // Overlay
  29374. if (parsedMesh.overlayAlpha !== undefined) {
  29375. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29376. }
  29377. if (parsedMesh.overlayColor !== undefined) {
  29378. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29379. }
  29380. if (parsedMesh.renderOverlay !== undefined) {
  29381. mesh.renderOverlay = parsedMesh.renderOverlay;
  29382. }
  29383. // Geometry
  29384. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29385. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29386. if (parsedMesh.delayLoadingFile) {
  29387. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29388. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29389. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29390. if (parsedMesh._binaryInfo) {
  29391. mesh._binaryInfo = parsedMesh._binaryInfo;
  29392. }
  29393. mesh._delayInfo = [];
  29394. if (parsedMesh.hasUVs) {
  29395. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29396. }
  29397. if (parsedMesh.hasUVs2) {
  29398. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29399. }
  29400. if (parsedMesh.hasUVs3) {
  29401. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29402. }
  29403. if (parsedMesh.hasUVs4) {
  29404. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29405. }
  29406. if (parsedMesh.hasUVs5) {
  29407. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29408. }
  29409. if (parsedMesh.hasUVs6) {
  29410. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29411. }
  29412. if (parsedMesh.hasColors) {
  29413. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29414. }
  29415. if (parsedMesh.hasMatricesIndices) {
  29416. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29417. }
  29418. if (parsedMesh.hasMatricesWeights) {
  29419. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29420. }
  29421. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29422. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29423. mesh._checkDelayState();
  29424. }
  29425. }
  29426. else {
  29427. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29428. }
  29429. // Material
  29430. if (parsedMesh.materialId) {
  29431. mesh.setMaterialByID(parsedMesh.materialId);
  29432. }
  29433. else {
  29434. mesh.material = null;
  29435. }
  29436. // Morph targets
  29437. if (parsedMesh.morphTargetManagerId > -1) {
  29438. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29439. }
  29440. // Skeleton
  29441. if (parsedMesh.skeletonId > -1) {
  29442. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29443. if (parsedMesh.numBoneInfluencers) {
  29444. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29445. }
  29446. }
  29447. // Animations
  29448. if (parsedMesh.animations) {
  29449. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29450. var parsedAnimation = parsedMesh.animations[animationIndex];
  29451. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29452. }
  29453. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29454. }
  29455. if (parsedMesh.autoAnimate) {
  29456. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29457. }
  29458. // Layer Mask
  29459. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29460. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29461. }
  29462. else {
  29463. mesh.layerMask = 0x0FFFFFFF;
  29464. }
  29465. // Physics
  29466. if (parsedMesh.physicsImpostor) {
  29467. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29468. mass: parsedMesh.physicsMass,
  29469. friction: parsedMesh.physicsFriction,
  29470. restitution: parsedMesh.physicsRestitution
  29471. }, scene);
  29472. }
  29473. // Instances
  29474. if (parsedMesh.instances) {
  29475. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29476. var parsedInstance = parsedMesh.instances[index];
  29477. var instance = mesh.createInstance(parsedInstance.name);
  29478. if (parsedInstance.id) {
  29479. instance.id = parsedInstance.id;
  29480. }
  29481. if (BABYLON.Tags) {
  29482. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29483. }
  29484. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29485. if (parsedInstance.parentId) {
  29486. instance._waitingParentId = parsedInstance.parentId;
  29487. }
  29488. if (parsedInstance.rotationQuaternion) {
  29489. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29490. }
  29491. else if (parsedInstance.rotation) {
  29492. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29493. }
  29494. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29495. instance.checkCollisions = mesh.checkCollisions;
  29496. if (parsedMesh.animations) {
  29497. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29498. parsedAnimation = parsedMesh.animations[animationIndex];
  29499. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29500. }
  29501. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29502. }
  29503. }
  29504. }
  29505. return mesh;
  29506. };
  29507. /**
  29508. * Creates a ribbon mesh.
  29509. * Please consider using the same method from the MeshBuilder class instead.
  29510. * 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.
  29511. *
  29512. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29513. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29514. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29515. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29516. * 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.
  29517. * 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.
  29518. * 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
  29519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29522. */
  29523. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29524. if (closeArray === void 0) { closeArray = false; }
  29525. if (updatable === void 0) { updatable = false; }
  29526. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29527. pathArray: pathArray,
  29528. closeArray: closeArray,
  29529. closePath: closePath,
  29530. offset: offset,
  29531. updatable: updatable,
  29532. sideOrientation: sideOrientation,
  29533. instance: instance
  29534. }, scene);
  29535. };
  29536. /**
  29537. * Creates a plane polygonal mesh. By default, this is a disc.
  29538. * Please consider using the same method from the MeshBuilder class instead.
  29539. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29540. * 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.
  29541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29544. */
  29545. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29546. if (scene === void 0) { scene = null; }
  29547. var options = {
  29548. radius: radius,
  29549. tessellation: tessellation,
  29550. sideOrientation: sideOrientation,
  29551. updatable: updatable
  29552. };
  29553. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29554. };
  29555. /**
  29556. * Creates a box mesh.
  29557. * Please consider using the same method from the MeshBuilder class instead.
  29558. * The parameter `size` sets the size (float) of each box side (default 1).
  29559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29562. */
  29563. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29564. if (scene === void 0) { scene = null; }
  29565. var options = {
  29566. size: size,
  29567. sideOrientation: sideOrientation,
  29568. updatable: updatable
  29569. };
  29570. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29571. };
  29572. /**
  29573. * Creates a sphere mesh.
  29574. * Please consider using the same method from the MeshBuilder class instead.
  29575. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29576. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29580. */
  29581. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29582. var options = {
  29583. segments: segments,
  29584. diameterX: diameter,
  29585. diameterY: diameter,
  29586. diameterZ: diameter,
  29587. sideOrientation: sideOrientation,
  29588. updatable: updatable
  29589. };
  29590. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29591. };
  29592. /**
  29593. * Creates a cylinder or a cone mesh.
  29594. * Please consider using the same method from the MeshBuilder class instead.
  29595. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29596. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29597. * 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.
  29598. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29599. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29600. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29601. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29603. */
  29604. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29605. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29606. if (scene !== undefined) {
  29607. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29608. updatable = scene;
  29609. }
  29610. scene = subdivisions;
  29611. subdivisions = 1;
  29612. }
  29613. var options = {
  29614. height: height,
  29615. diameterTop: diameterTop,
  29616. diameterBottom: diameterBottom,
  29617. tessellation: tessellation,
  29618. subdivisions: subdivisions,
  29619. sideOrientation: sideOrientation,
  29620. updatable: updatable
  29621. };
  29622. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29623. };
  29624. // Torus (Code from SharpDX.org)
  29625. /**
  29626. * Creates a torus mesh.
  29627. * Please consider using the same method from the MeshBuilder class instead.
  29628. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29629. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29630. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29632. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29634. */
  29635. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29636. var options = {
  29637. diameter: diameter,
  29638. thickness: thickness,
  29639. tessellation: tessellation,
  29640. sideOrientation: sideOrientation,
  29641. updatable: updatable
  29642. };
  29643. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29644. };
  29645. /**
  29646. * Creates a torus knot mesh.
  29647. * Please consider using the same method from the MeshBuilder class instead.
  29648. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29649. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29650. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29651. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29653. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29655. */
  29656. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29657. var options = {
  29658. radius: radius,
  29659. tube: tube,
  29660. radialSegments: radialSegments,
  29661. tubularSegments: tubularSegments,
  29662. p: p,
  29663. q: q,
  29664. sideOrientation: sideOrientation,
  29665. updatable: updatable
  29666. };
  29667. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29668. };
  29669. /**
  29670. * Creates a line mesh.
  29671. * Please consider using the same method from the MeshBuilder class instead.
  29672. * 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.
  29673. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29674. * The parameter `points` is an array successive Vector3.
  29675. * 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
  29676. * When updating an instance, remember that only point positions can change, not the number of points.
  29677. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29678. */
  29679. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29680. if (scene === void 0) { scene = null; }
  29681. if (updatable === void 0) { updatable = false; }
  29682. if (instance === void 0) { instance = null; }
  29683. var options = {
  29684. points: points,
  29685. updatable: updatable,
  29686. instance: instance
  29687. };
  29688. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29689. };
  29690. /**
  29691. * Creates a dashed line mesh.
  29692. * Please consider using the same method from the MeshBuilder class instead.
  29693. * 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.
  29694. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29695. * The parameter `points` is an array successive Vector3.
  29696. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29697. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29698. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29699. * 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
  29700. * When updating an instance, remember that only point positions can change, not the number of points.
  29701. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29702. */
  29703. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29704. if (scene === void 0) { scene = null; }
  29705. var options = {
  29706. points: points,
  29707. dashSize: dashSize,
  29708. gapSize: gapSize,
  29709. dashNb: dashNb,
  29710. updatable: updatable,
  29711. instance: instance
  29712. };
  29713. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29714. };
  29715. /**
  29716. * Creates a polygon mesh.
  29717. * Please consider using the same method from the MeshBuilder class instead.
  29718. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29719. * 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.
  29720. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29722. * Remember you can only change the shape positions, not their number when updating a polygon.
  29723. */
  29724. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29725. var options = {
  29726. shape: shape,
  29727. holes: holes,
  29728. updatable: updatable,
  29729. sideOrientation: sideOrientation
  29730. };
  29731. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29732. };
  29733. /**
  29734. * Creates an extruded polygon mesh, with depth in the Y direction.
  29735. * Please consider using the same method from the MeshBuilder class instead.
  29736. */
  29737. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29738. var options = {
  29739. shape: shape,
  29740. holes: holes,
  29741. depth: depth,
  29742. updatable: updatable,
  29743. sideOrientation: sideOrientation
  29744. };
  29745. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29746. };
  29747. /**
  29748. * Creates an extruded shape mesh.
  29749. * 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.
  29750. * Please consider using the same method from the MeshBuilder class instead.
  29751. *
  29752. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29753. * 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
  29754. * extruded along the Z axis.
  29755. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29756. * 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.
  29757. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29758. * 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
  29759. * 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
  29760. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29761. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29762. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29764. */
  29765. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29766. if (scene === void 0) { scene = null; }
  29767. var options = {
  29768. shape: shape,
  29769. path: path,
  29770. scale: scale,
  29771. rotation: rotation,
  29772. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29773. sideOrientation: sideOrientation,
  29774. instance: instance,
  29775. updatable: updatable
  29776. };
  29777. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29778. };
  29779. /**
  29780. * Creates an custom extruded shape mesh.
  29781. * 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.
  29782. * Please consider using the same method from the MeshBuilder class instead.
  29783. *
  29784. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29785. * 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
  29786. * extruded along the Z axis.
  29787. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29788. * 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
  29789. * and the distance of this point from the begining of the path :
  29790. * ```javascript
  29791. * var rotationFunction = function(i, distance) {
  29792. * // do things
  29793. * return rotationValue; }
  29794. * ```
  29795. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29796. * 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
  29797. * and the distance of this point from the begining of the path :
  29798. * ```javascript
  29799. * var scaleFunction = function(i, distance) {
  29800. * // do things
  29801. * return scaleValue;}
  29802. * ```
  29803. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29804. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29805. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29806. * 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
  29807. * 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
  29808. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29810. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29811. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29812. */
  29813. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29814. var options = {
  29815. shape: shape,
  29816. path: path,
  29817. scaleFunction: scaleFunction,
  29818. rotationFunction: rotationFunction,
  29819. ribbonCloseArray: ribbonCloseArray,
  29820. ribbonClosePath: ribbonClosePath,
  29821. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29822. sideOrientation: sideOrientation,
  29823. instance: instance,
  29824. updatable: updatable
  29825. };
  29826. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29827. };
  29828. /**
  29829. * Creates lathe mesh.
  29830. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29831. * Please consider using the same method from the MeshBuilder class instead.
  29832. * 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
  29833. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29834. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29835. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29836. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29837. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29839. */
  29840. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29841. var options = {
  29842. shape: shape,
  29843. radius: radius,
  29844. tessellation: tessellation,
  29845. sideOrientation: sideOrientation,
  29846. updatable: updatable
  29847. };
  29848. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29849. };
  29850. /**
  29851. * Creates a plane mesh.
  29852. * Please consider using the same method from the MeshBuilder class instead.
  29853. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29855. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29857. */
  29858. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29859. var options = {
  29860. size: size,
  29861. width: size,
  29862. height: size,
  29863. sideOrientation: sideOrientation,
  29864. updatable: updatable
  29865. };
  29866. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29867. };
  29868. /**
  29869. * Creates a ground mesh.
  29870. * Please consider using the same method from the MeshBuilder class instead.
  29871. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29872. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29874. */
  29875. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29876. var options = {
  29877. width: width,
  29878. height: height,
  29879. subdivisions: subdivisions,
  29880. updatable: updatable
  29881. };
  29882. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29883. };
  29884. /**
  29885. * Creates a tiled ground mesh.
  29886. * Please consider using the same method from the MeshBuilder class instead.
  29887. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29888. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29889. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29890. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29891. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29892. * numbers of subdivisions on the ground width and height of each tile.
  29893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29894. */
  29895. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29896. var options = {
  29897. xmin: xmin,
  29898. zmin: zmin,
  29899. xmax: xmax,
  29900. zmax: zmax,
  29901. subdivisions: subdivisions,
  29902. precision: precision,
  29903. updatable: updatable
  29904. };
  29905. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29906. };
  29907. /**
  29908. * Creates a ground mesh from a height map.
  29909. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29910. * Please consider using the same method from the MeshBuilder class instead.
  29911. * The parameter `url` sets the URL of the height map image resource.
  29912. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29913. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29914. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29915. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29916. * 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).
  29917. * This function is passed the newly built mesh :
  29918. * ```javascript
  29919. * function(mesh) { // do things
  29920. * return; }
  29921. * ```
  29922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29923. */
  29924. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29925. var options = {
  29926. width: width,
  29927. height: height,
  29928. subdivisions: subdivisions,
  29929. minHeight: minHeight,
  29930. maxHeight: maxHeight,
  29931. updatable: updatable,
  29932. onReady: onReady
  29933. };
  29934. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29935. };
  29936. /**
  29937. * Creates a tube mesh.
  29938. * 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.
  29939. * Please consider using the same method from the MeshBuilder class instead.
  29940. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29941. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29942. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29943. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29944. * 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.
  29945. * It must return a radius value (positive float) :
  29946. * ```javascript
  29947. * var radiusFunction = function(i, distance) {
  29948. * // do things
  29949. * return radius; }
  29950. * ```
  29951. * 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
  29952. * 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
  29953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29956. */
  29957. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29958. var options = {
  29959. path: path,
  29960. radius: radius,
  29961. tessellation: tessellation,
  29962. radiusFunction: radiusFunction,
  29963. arc: 1,
  29964. cap: cap,
  29965. updatable: updatable,
  29966. sideOrientation: sideOrientation,
  29967. instance: instance
  29968. };
  29969. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29970. };
  29971. /**
  29972. * Creates a polyhedron mesh.
  29973. * Please consider using the same method from the MeshBuilder class instead.
  29974. * 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
  29975. * to choose the wanted type.
  29976. * The parameter `size` (positive float, default 1) sets the polygon size.
  29977. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29978. * 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`.
  29979. * 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
  29980. * 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)`).
  29981. * 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
  29982. * 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.
  29983. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29984. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29986. */
  29987. Mesh.CreatePolyhedron = function (name, options, scene) {
  29988. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29989. };
  29990. /**
  29991. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29992. * Please consider using the same method from the MeshBuilder class instead.
  29993. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29994. * 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`).
  29995. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29996. * 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.
  29997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29998. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30000. */
  30001. Mesh.CreateIcoSphere = function (name, options, scene) {
  30002. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30003. };
  30004. /**
  30005. * Creates a decal mesh.
  30006. * Please consider using the same method from the MeshBuilder class instead.
  30007. * 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.
  30008. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30009. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30010. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30011. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30012. */
  30013. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30014. var options = {
  30015. position: position,
  30016. normal: normal,
  30017. size: size,
  30018. angle: angle
  30019. };
  30020. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30021. };
  30022. // Skeletons
  30023. /**
  30024. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30025. */
  30026. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30027. if (!this._sourcePositions) {
  30028. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30029. if (!source) {
  30030. return this._sourcePositions;
  30031. }
  30032. this._sourcePositions = new Float32Array(source);
  30033. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30034. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30035. }
  30036. }
  30037. return this._sourcePositions;
  30038. };
  30039. /**
  30040. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30041. */
  30042. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30043. if (!this._sourceNormals) {
  30044. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30045. if (!source) {
  30046. return this._sourceNormals;
  30047. }
  30048. this._sourceNormals = new Float32Array(source);
  30049. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30050. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30051. }
  30052. }
  30053. return this._sourceNormals;
  30054. };
  30055. /**
  30056. * Updates the vertex buffer by applying transformation from the bones.
  30057. * Returns the Mesh.
  30058. *
  30059. * @param {skeleton} skeleton to apply
  30060. */
  30061. Mesh.prototype.applySkeleton = function (skeleton) {
  30062. if (!this.geometry) {
  30063. return this;
  30064. }
  30065. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30066. return this;
  30067. }
  30068. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30069. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30070. return this;
  30071. }
  30072. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30073. return this;
  30074. }
  30075. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30076. return this;
  30077. }
  30078. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30079. return this;
  30080. }
  30081. if (!this._sourcePositions) {
  30082. var submeshes = this.subMeshes.slice();
  30083. this.setPositionsForCPUSkinning();
  30084. this.subMeshes = submeshes;
  30085. }
  30086. if (!this._sourceNormals) {
  30087. this.setNormalsForCPUSkinning();
  30088. }
  30089. // positionsData checks for not being Float32Array will only pass at most once
  30090. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30091. if (!positionsData) {
  30092. return this;
  30093. }
  30094. if (!(positionsData instanceof Float32Array)) {
  30095. positionsData = new Float32Array(positionsData);
  30096. }
  30097. // normalsData checks for not being Float32Array will only pass at most once
  30098. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30099. if (!normalsData) {
  30100. return this;
  30101. }
  30102. if (!(normalsData instanceof Float32Array)) {
  30103. normalsData = new Float32Array(normalsData);
  30104. }
  30105. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30106. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30107. if (!matricesWeightsData || !matricesIndicesData) {
  30108. return this;
  30109. }
  30110. var needExtras = this.numBoneInfluencers > 4;
  30111. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30112. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30113. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30114. var tempVector3 = BABYLON.Vector3.Zero();
  30115. var finalMatrix = new BABYLON.Matrix();
  30116. var tempMatrix = new BABYLON.Matrix();
  30117. var matWeightIdx = 0;
  30118. var inf;
  30119. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30120. var weight;
  30121. for (inf = 0; inf < 4; inf++) {
  30122. weight = matricesWeightsData[matWeightIdx + inf];
  30123. if (weight > 0) {
  30124. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30125. finalMatrix.addToSelf(tempMatrix);
  30126. }
  30127. else
  30128. break;
  30129. }
  30130. if (needExtras) {
  30131. for (inf = 0; inf < 4; inf++) {
  30132. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30133. if (weight > 0) {
  30134. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30135. finalMatrix.addToSelf(tempMatrix);
  30136. }
  30137. else
  30138. break;
  30139. }
  30140. }
  30141. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30142. tempVector3.toArray(positionsData, index);
  30143. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30144. tempVector3.toArray(normalsData, index);
  30145. finalMatrix.reset();
  30146. }
  30147. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30148. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30149. return this;
  30150. };
  30151. // Tools
  30152. /**
  30153. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30154. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30155. */
  30156. Mesh.MinMax = function (meshes) {
  30157. var minVector = null;
  30158. var maxVector = null;
  30159. meshes.forEach(function (mesh, index, array) {
  30160. var boundingInfo = mesh.getBoundingInfo();
  30161. var boundingBox = boundingInfo.boundingBox;
  30162. if (!minVector || !maxVector) {
  30163. minVector = boundingBox.minimumWorld;
  30164. maxVector = boundingBox.maximumWorld;
  30165. }
  30166. else {
  30167. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30168. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30169. }
  30170. });
  30171. if (!minVector || !maxVector) {
  30172. return {
  30173. min: BABYLON.Vector3.Zero(),
  30174. max: BABYLON.Vector3.Zero()
  30175. };
  30176. }
  30177. return {
  30178. min: minVector,
  30179. max: maxVector
  30180. };
  30181. };
  30182. /**
  30183. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30184. */
  30185. Mesh.Center = function (meshesOrMinMaxVector) {
  30186. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30187. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30188. };
  30189. /**
  30190. * Merge the array of meshes into a single mesh for performance reasons.
  30191. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30192. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30193. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30194. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30195. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30196. */
  30197. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30198. if (disposeSource === void 0) { disposeSource = true; }
  30199. var index;
  30200. if (!allow32BitsIndices) {
  30201. var totalVertices = 0;
  30202. // Counting vertices
  30203. for (index = 0; index < meshes.length; index++) {
  30204. if (meshes[index]) {
  30205. totalVertices += meshes[index].getTotalVertices();
  30206. if (totalVertices > 65536) {
  30207. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30208. return null;
  30209. }
  30210. }
  30211. }
  30212. }
  30213. // Merge
  30214. var vertexData = null;
  30215. var otherVertexData;
  30216. var indiceArray = new Array();
  30217. var source = null;
  30218. for (index = 0; index < meshes.length; index++) {
  30219. if (meshes[index]) {
  30220. meshes[index].computeWorldMatrix(true);
  30221. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30222. otherVertexData.transform(meshes[index].getWorldMatrix());
  30223. if (vertexData) {
  30224. vertexData.merge(otherVertexData);
  30225. }
  30226. else {
  30227. vertexData = otherVertexData;
  30228. source = meshes[index];
  30229. }
  30230. if (subdivideWithSubMeshes) {
  30231. indiceArray.push(meshes[index].getTotalIndices());
  30232. }
  30233. }
  30234. }
  30235. source = source;
  30236. if (!meshSubclass) {
  30237. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30238. }
  30239. vertexData.applyToMesh(meshSubclass);
  30240. // Setting properties
  30241. meshSubclass.material = source.material;
  30242. meshSubclass.checkCollisions = source.checkCollisions;
  30243. // Cleaning
  30244. if (disposeSource) {
  30245. for (index = 0; index < meshes.length; index++) {
  30246. if (meshes[index]) {
  30247. meshes[index].dispose();
  30248. }
  30249. }
  30250. }
  30251. // Subdivide
  30252. if (subdivideWithSubMeshes) {
  30253. //-- Suppresions du submesh global
  30254. meshSubclass.releaseSubMeshes();
  30255. index = 0;
  30256. var offset = 0;
  30257. //-- aplique la subdivision en fonction du tableau d'indices
  30258. while (index < indiceArray.length) {
  30259. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30260. offset += indiceArray[index];
  30261. index++;
  30262. }
  30263. }
  30264. return meshSubclass;
  30265. };
  30266. // Consts
  30267. Mesh._FRONTSIDE = 0;
  30268. Mesh._BACKSIDE = 1;
  30269. Mesh._DOUBLESIDE = 2;
  30270. Mesh._DEFAULTSIDE = 0;
  30271. Mesh._NO_CAP = 0;
  30272. Mesh._CAP_START = 1;
  30273. Mesh._CAP_END = 2;
  30274. Mesh._CAP_ALL = 3;
  30275. return Mesh;
  30276. }(BABYLON.AbstractMesh));
  30277. BABYLON.Mesh = Mesh;
  30278. })(BABYLON || (BABYLON = {}));
  30279. //# sourceMappingURL=babylon.mesh.js.map
  30280. var BABYLON;
  30281. (function (BABYLON) {
  30282. var BaseSubMesh = /** @class */ (function () {
  30283. function BaseSubMesh() {
  30284. }
  30285. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30286. get: function () {
  30287. return this._materialEffect;
  30288. },
  30289. enumerable: true,
  30290. configurable: true
  30291. });
  30292. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30293. if (defines === void 0) { defines = null; }
  30294. if (this._materialEffect === effect) {
  30295. if (!effect) {
  30296. this._materialDefines = null;
  30297. }
  30298. return;
  30299. }
  30300. this._materialDefines = defines;
  30301. this._materialEffect = effect;
  30302. };
  30303. return BaseSubMesh;
  30304. }());
  30305. BABYLON.BaseSubMesh = BaseSubMesh;
  30306. var SubMesh = /** @class */ (function (_super) {
  30307. __extends(SubMesh, _super);
  30308. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30309. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30310. var _this = _super.call(this) || this;
  30311. _this.materialIndex = materialIndex;
  30312. _this.verticesStart = verticesStart;
  30313. _this.verticesCount = verticesCount;
  30314. _this.indexStart = indexStart;
  30315. _this.indexCount = indexCount;
  30316. _this._renderId = 0;
  30317. _this._mesh = mesh;
  30318. _this._renderingMesh = renderingMesh || mesh;
  30319. mesh.subMeshes.push(_this);
  30320. _this._trianglePlanes = [];
  30321. _this._id = mesh.subMeshes.length - 1;
  30322. if (createBoundingBox) {
  30323. _this.refreshBoundingInfo();
  30324. mesh.computeWorldMatrix(true);
  30325. }
  30326. return _this;
  30327. }
  30328. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30329. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30330. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30331. };
  30332. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30333. get: function () {
  30334. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30335. },
  30336. enumerable: true,
  30337. configurable: true
  30338. });
  30339. /**
  30340. * Returns the submesh BoudingInfo object.
  30341. */
  30342. SubMesh.prototype.getBoundingInfo = function () {
  30343. if (this.IsGlobal) {
  30344. return this._mesh.getBoundingInfo();
  30345. }
  30346. return this._boundingInfo;
  30347. };
  30348. /**
  30349. * Sets the submesh BoundingInfo.
  30350. * Return the SubMesh.
  30351. */
  30352. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30353. this._boundingInfo = boundingInfo;
  30354. return this;
  30355. };
  30356. /**
  30357. * Returns the mesh of the current submesh.
  30358. */
  30359. SubMesh.prototype.getMesh = function () {
  30360. return this._mesh;
  30361. };
  30362. /**
  30363. * Returns the rendering mesh of the submesh.
  30364. */
  30365. SubMesh.prototype.getRenderingMesh = function () {
  30366. return this._renderingMesh;
  30367. };
  30368. /**
  30369. * Returns the submesh material.
  30370. */
  30371. SubMesh.prototype.getMaterial = function () {
  30372. var rootMaterial = this._renderingMesh.material;
  30373. if (rootMaterial === null || rootMaterial === undefined) {
  30374. return this._mesh.getScene().defaultMaterial;
  30375. }
  30376. else if (rootMaterial.getSubMaterial) {
  30377. var multiMaterial = rootMaterial;
  30378. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30379. if (this._currentMaterial !== effectiveMaterial) {
  30380. this._currentMaterial = effectiveMaterial;
  30381. this._materialDefines = null;
  30382. }
  30383. return effectiveMaterial;
  30384. }
  30385. return rootMaterial;
  30386. };
  30387. // Methods
  30388. /**
  30389. * Sets a new updated BoundingInfo object to the submesh.
  30390. * Returns the SubMesh.
  30391. */
  30392. SubMesh.prototype.refreshBoundingInfo = function () {
  30393. this._lastColliderWorldVertices = null;
  30394. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30395. return this;
  30396. }
  30397. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30398. if (!data) {
  30399. this._boundingInfo = this._mesh.getBoundingInfo();
  30400. return this;
  30401. }
  30402. var indices = this._renderingMesh.getIndices();
  30403. var extend;
  30404. //is this the only submesh?
  30405. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30406. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30407. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30408. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30409. }
  30410. else {
  30411. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30412. }
  30413. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30414. return this;
  30415. };
  30416. SubMesh.prototype._checkCollision = function (collider) {
  30417. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30418. return boundingInfo._checkCollision(collider);
  30419. };
  30420. /**
  30421. * Updates the submesh BoundingInfo.
  30422. * Returns the Submesh.
  30423. */
  30424. SubMesh.prototype.updateBoundingInfo = function (world) {
  30425. var boundingInfo = this.getBoundingInfo();
  30426. if (!boundingInfo) {
  30427. this.refreshBoundingInfo();
  30428. boundingInfo = this.getBoundingInfo();
  30429. }
  30430. boundingInfo.update(world);
  30431. return this;
  30432. };
  30433. /**
  30434. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30435. * Boolean returned.
  30436. */
  30437. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30438. var boundingInfo = this.getBoundingInfo();
  30439. if (!boundingInfo) {
  30440. return false;
  30441. }
  30442. return boundingInfo.isInFrustum(frustumPlanes);
  30443. };
  30444. /**
  30445. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30446. * Boolean returned.
  30447. */
  30448. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30449. var boundingInfo = this.getBoundingInfo();
  30450. if (!boundingInfo) {
  30451. return false;
  30452. }
  30453. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30454. };
  30455. /**
  30456. * Renders the submesh.
  30457. * Returns it.
  30458. */
  30459. SubMesh.prototype.render = function (enableAlphaMode) {
  30460. this._renderingMesh.render(this, enableAlphaMode);
  30461. return this;
  30462. };
  30463. /**
  30464. * Returns a new Index Buffer.
  30465. * Type returned : WebGLBuffer.
  30466. */
  30467. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30468. if (!this._linesIndexBuffer) {
  30469. var linesIndices = [];
  30470. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30471. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30472. }
  30473. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30474. this.linesIndexCount = linesIndices.length;
  30475. }
  30476. return this._linesIndexBuffer;
  30477. };
  30478. /**
  30479. * True is the passed Ray intersects the submesh bounding box.
  30480. * Boolean returned.
  30481. */
  30482. SubMesh.prototype.canIntersects = function (ray) {
  30483. var boundingInfo = this.getBoundingInfo();
  30484. if (!boundingInfo) {
  30485. return false;
  30486. }
  30487. return ray.intersectsBox(boundingInfo.boundingBox);
  30488. };
  30489. /**
  30490. * Returns an object IntersectionInfo.
  30491. */
  30492. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30493. var intersectInfo = null;
  30494. // LineMesh first as it's also a Mesh...
  30495. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30496. var lineMesh = this._mesh;
  30497. // Line test
  30498. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30499. var p0 = positions[indices[index]];
  30500. var p1 = positions[indices[index + 1]];
  30501. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30502. if (length < 0) {
  30503. continue;
  30504. }
  30505. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30506. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30507. if (fastCheck) {
  30508. break;
  30509. }
  30510. }
  30511. }
  30512. }
  30513. else {
  30514. // Triangles test
  30515. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30516. var p0 = positions[indices[index]];
  30517. var p1 = positions[indices[index + 1]];
  30518. var p2 = positions[indices[index + 2]];
  30519. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30520. if (currentIntersectInfo) {
  30521. if (currentIntersectInfo.distance < 0) {
  30522. continue;
  30523. }
  30524. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30525. intersectInfo = currentIntersectInfo;
  30526. intersectInfo.faceId = index / 3;
  30527. if (fastCheck) {
  30528. break;
  30529. }
  30530. }
  30531. }
  30532. }
  30533. }
  30534. return intersectInfo;
  30535. };
  30536. SubMesh.prototype._rebuild = function () {
  30537. if (this._linesIndexBuffer) {
  30538. this._linesIndexBuffer = null;
  30539. }
  30540. };
  30541. // Clone
  30542. /**
  30543. * Creates a new Submesh from the passed Mesh.
  30544. */
  30545. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30546. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30547. if (!this.IsGlobal) {
  30548. var boundingInfo = this.getBoundingInfo();
  30549. if (!boundingInfo) {
  30550. return result;
  30551. }
  30552. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30553. }
  30554. return result;
  30555. };
  30556. // Dispose
  30557. /**
  30558. * Disposes the Submesh.
  30559. * Returns nothing.
  30560. */
  30561. SubMesh.prototype.dispose = function () {
  30562. if (this._linesIndexBuffer) {
  30563. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30564. this._linesIndexBuffer = null;
  30565. }
  30566. // Remove from mesh
  30567. var index = this._mesh.subMeshes.indexOf(this);
  30568. this._mesh.subMeshes.splice(index, 1);
  30569. };
  30570. // Statics
  30571. /**
  30572. * Creates a new Submesh from the passed parameters :
  30573. * - materialIndex (integer) : the index of the main mesh material.
  30574. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30575. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30576. * - mesh (Mesh) : the main mesh to create the submesh from.
  30577. * - renderingMesh (optional Mesh) : rendering mesh.
  30578. */
  30579. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30580. var minVertexIndex = Number.MAX_VALUE;
  30581. var maxVertexIndex = -Number.MAX_VALUE;
  30582. renderingMesh = (renderingMesh || mesh);
  30583. var indices = renderingMesh.getIndices();
  30584. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30585. var vertexIndex = indices[index];
  30586. if (vertexIndex < minVertexIndex)
  30587. minVertexIndex = vertexIndex;
  30588. if (vertexIndex > maxVertexIndex)
  30589. maxVertexIndex = vertexIndex;
  30590. }
  30591. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30592. };
  30593. return SubMesh;
  30594. }(BaseSubMesh));
  30595. BABYLON.SubMesh = SubMesh;
  30596. })(BABYLON || (BABYLON = {}));
  30597. //# sourceMappingURL=babylon.subMesh.js.map
  30598. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30599. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30600. s = arguments[i];
  30601. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30602. t[p] = s[p];
  30603. }
  30604. return t;
  30605. };
  30606. var BABYLON;
  30607. (function (BABYLON) {
  30608. /**
  30609. * Manages the defines for the Material.
  30610. */
  30611. var MaterialDefines = /** @class */ (function () {
  30612. function MaterialDefines() {
  30613. this._isDirty = true;
  30614. this._areLightsDirty = true;
  30615. this._areAttributesDirty = true;
  30616. this._areTexturesDirty = true;
  30617. this._areFresnelDirty = true;
  30618. this._areMiscDirty = true;
  30619. this._areImageProcessingDirty = true;
  30620. this._normals = false;
  30621. this._uvs = false;
  30622. this._needNormals = false;
  30623. this._needUVs = false;
  30624. }
  30625. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30626. /**
  30627. * Specifies if the material needs to be re-calculated.
  30628. */
  30629. get: function () {
  30630. return this._isDirty;
  30631. },
  30632. enumerable: true,
  30633. configurable: true
  30634. });
  30635. /**
  30636. * Marks the material to indicate that it has been re-calculated.
  30637. */
  30638. MaterialDefines.prototype.markAsProcessed = function () {
  30639. this._isDirty = false;
  30640. this._areAttributesDirty = false;
  30641. this._areTexturesDirty = false;
  30642. this._areFresnelDirty = false;
  30643. this._areLightsDirty = false;
  30644. this._areMiscDirty = false;
  30645. this._areImageProcessingDirty = false;
  30646. };
  30647. /**
  30648. * Marks the material to indicate that it needs to be re-calculated.
  30649. */
  30650. MaterialDefines.prototype.markAsUnprocessed = function () {
  30651. this._isDirty = true;
  30652. };
  30653. /**
  30654. * Marks the material to indicate all of its defines need to be re-calculated.
  30655. */
  30656. MaterialDefines.prototype.markAllAsDirty = function () {
  30657. this._areTexturesDirty = true;
  30658. this._areAttributesDirty = true;
  30659. this._areLightsDirty = true;
  30660. this._areFresnelDirty = true;
  30661. this._areMiscDirty = true;
  30662. this._areImageProcessingDirty = true;
  30663. this._isDirty = true;
  30664. };
  30665. /**
  30666. * Marks the material to indicate that image processing needs to be re-calculated.
  30667. */
  30668. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30669. this._areImageProcessingDirty = true;
  30670. this._isDirty = true;
  30671. };
  30672. /**
  30673. * Marks the material to indicate the lights need to be re-calculated.
  30674. */
  30675. MaterialDefines.prototype.markAsLightDirty = function () {
  30676. this._areLightsDirty = true;
  30677. this._isDirty = true;
  30678. };
  30679. /**
  30680. * Marks the attribute state as changed.
  30681. */
  30682. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30683. this._areAttributesDirty = true;
  30684. this._isDirty = true;
  30685. };
  30686. /**
  30687. * Marks the texture state as changed.
  30688. */
  30689. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30690. this._areTexturesDirty = true;
  30691. this._isDirty = true;
  30692. };
  30693. /**
  30694. * Marks the fresnel state as changed.
  30695. */
  30696. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30697. this._areFresnelDirty = true;
  30698. this._isDirty = true;
  30699. };
  30700. /**
  30701. * Marks the misc state as changed.
  30702. */
  30703. MaterialDefines.prototype.markAsMiscDirty = function () {
  30704. this._areMiscDirty = true;
  30705. this._isDirty = true;
  30706. };
  30707. /**
  30708. * Rebuilds the material defines.
  30709. */
  30710. MaterialDefines.prototype.rebuild = function () {
  30711. if (this._keys) {
  30712. delete this._keys;
  30713. }
  30714. this._keys = [];
  30715. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30716. var key = _a[_i];
  30717. if (key[0] === "_") {
  30718. continue;
  30719. }
  30720. this._keys.push(key);
  30721. }
  30722. };
  30723. /**
  30724. * Specifies if two material defines are equal.
  30725. * @param other - A material define instance to compare to.
  30726. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30727. */
  30728. MaterialDefines.prototype.isEqual = function (other) {
  30729. if (this._keys.length !== other._keys.length) {
  30730. return false;
  30731. }
  30732. for (var index = 0; index < this._keys.length; index++) {
  30733. var prop = this._keys[index];
  30734. if (this[prop] !== other[prop]) {
  30735. return false;
  30736. }
  30737. }
  30738. return true;
  30739. };
  30740. /**
  30741. * Clones this instance's defines to another instance.
  30742. * @param other - material defines to clone values to.
  30743. */
  30744. MaterialDefines.prototype.cloneTo = function (other) {
  30745. if (this._keys.length !== other._keys.length) {
  30746. other._keys = this._keys.slice(0);
  30747. }
  30748. for (var index = 0; index < this._keys.length; index++) {
  30749. var prop = this._keys[index];
  30750. other[prop] = this[prop];
  30751. }
  30752. };
  30753. /**
  30754. * Resets the material define values.
  30755. */
  30756. MaterialDefines.prototype.reset = function () {
  30757. for (var index = 0; index < this._keys.length; index++) {
  30758. var prop = this._keys[index];
  30759. if (typeof (this[prop]) === "number") {
  30760. this[prop] = 0;
  30761. }
  30762. else {
  30763. this[prop] = false;
  30764. }
  30765. }
  30766. };
  30767. /**
  30768. * Converts the material define values to a string.
  30769. * @returns - String of material define information.
  30770. */
  30771. MaterialDefines.prototype.toString = function () {
  30772. var result = "";
  30773. for (var index = 0; index < this._keys.length; index++) {
  30774. var prop = this._keys[index];
  30775. var value = this[prop];
  30776. if (typeof (value) === "number") {
  30777. result += "#define " + prop + " " + this[prop] + "\n";
  30778. }
  30779. else if (value) {
  30780. result += "#define " + prop + "\n";
  30781. }
  30782. }
  30783. return result;
  30784. };
  30785. return MaterialDefines;
  30786. }());
  30787. BABYLON.MaterialDefines = MaterialDefines;
  30788. /**
  30789. * This offers the main features of a material in BJS.
  30790. */
  30791. var Material = /** @class */ (function () {
  30792. /**
  30793. * Creates a material instance.
  30794. * @param name - The name of the material.
  30795. * @param scene - The BJS scene to reference.
  30796. * @param doNotAdd - Specifies if the material should be added to the scene.
  30797. */
  30798. function Material(name, scene, doNotAdd) {
  30799. /**
  30800. * Specifies if the ready state should be checked on each call.
  30801. */
  30802. this.checkReadyOnEveryCall = false;
  30803. /**
  30804. * Specifies if the ready state should be checked once.
  30805. */
  30806. this.checkReadyOnlyOnce = false;
  30807. /**
  30808. * The state of the material.
  30809. */
  30810. this.state = "";
  30811. /**
  30812. * The alpha value of the material.
  30813. */
  30814. this._alpha = 1.0;
  30815. /**
  30816. * Specifies if back face culling is enabled.
  30817. */
  30818. this._backFaceCulling = true;
  30819. /**
  30820. * Specifies if the material should be serialized.
  30821. */
  30822. this.doNotSerialize = false;
  30823. /**
  30824. * Specifies if the effect should be stored on sub meshes.
  30825. */
  30826. this.storeEffectOnSubMeshes = false;
  30827. /**
  30828. * An event triggered when the material is disposed.
  30829. * @type {BABYLON.Observable}
  30830. */
  30831. this.onDisposeObservable = new BABYLON.Observable();
  30832. /**
  30833. * An event triggered when the material is bound.
  30834. * @type {BABYLON.Observable}
  30835. */
  30836. this.onBindObservable = new BABYLON.Observable();
  30837. /**
  30838. * An event triggered when the material is unbound.
  30839. * @type {BABYLON.Observable}
  30840. */
  30841. this.onUnBindObservable = new BABYLON.Observable();
  30842. /**
  30843. * Stores the value of the alpha mode.
  30844. */
  30845. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30846. /**
  30847. * Stores the state of the need depth pre-pass value.
  30848. */
  30849. this._needDepthPrePass = false;
  30850. /**
  30851. * Specifies if depth writing should be disabled.
  30852. */
  30853. this.disableDepthWrite = false;
  30854. /**
  30855. * Specifies if depth writing should be forced.
  30856. */
  30857. this.forceDepthWrite = false;
  30858. /**
  30859. * Specifies if there should be a separate pass for culling.
  30860. */
  30861. this.separateCullingPass = false;
  30862. /**
  30863. * Stores the state specifing if fog should be enabled.
  30864. */
  30865. this._fogEnabled = true;
  30866. /**
  30867. * Stores the size of points.
  30868. */
  30869. this.pointSize = 1.0;
  30870. /**
  30871. * Stores the z offset value.
  30872. */
  30873. this.zOffset = 0;
  30874. /**
  30875. * Specifies if the material was previously ready.
  30876. */
  30877. this._wasPreviouslyReady = false;
  30878. /**
  30879. * Stores the fill mode state.
  30880. */
  30881. this._fillMode = Material.TriangleFillMode;
  30882. this.name = name;
  30883. this.id = name || BABYLON.Tools.RandomId();
  30884. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30885. if (this._scene.useRightHandedSystem) {
  30886. this.sideOrientation = Material.ClockWiseSideOrientation;
  30887. }
  30888. else {
  30889. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30890. }
  30891. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30892. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30893. if (!doNotAdd) {
  30894. this._scene.materials.push(this);
  30895. }
  30896. }
  30897. Object.defineProperty(Material, "TriangleFillMode", {
  30898. /**
  30899. * Returns the triangle fill mode.
  30900. */
  30901. get: function () {
  30902. return Material._TriangleFillMode;
  30903. },
  30904. enumerable: true,
  30905. configurable: true
  30906. });
  30907. Object.defineProperty(Material, "WireFrameFillMode", {
  30908. /**
  30909. * Returns the wireframe mode.
  30910. */
  30911. get: function () {
  30912. return Material._WireFrameFillMode;
  30913. },
  30914. enumerable: true,
  30915. configurable: true
  30916. });
  30917. Object.defineProperty(Material, "PointFillMode", {
  30918. /**
  30919. * Returns the point fill mode.
  30920. */
  30921. get: function () {
  30922. return Material._PointFillMode;
  30923. },
  30924. enumerable: true,
  30925. configurable: true
  30926. });
  30927. Object.defineProperty(Material, "PointListDrawMode", {
  30928. /**
  30929. * Returns the point list draw mode.
  30930. */
  30931. get: function () {
  30932. return Material._PointListDrawMode;
  30933. },
  30934. enumerable: true,
  30935. configurable: true
  30936. });
  30937. Object.defineProperty(Material, "LineListDrawMode", {
  30938. /**
  30939. * Returns the line list draw mode.
  30940. */
  30941. get: function () {
  30942. return Material._LineListDrawMode;
  30943. },
  30944. enumerable: true,
  30945. configurable: true
  30946. });
  30947. Object.defineProperty(Material, "LineLoopDrawMode", {
  30948. /**
  30949. * Returns the line loop draw mode.
  30950. */
  30951. get: function () {
  30952. return Material._LineLoopDrawMode;
  30953. },
  30954. enumerable: true,
  30955. configurable: true
  30956. });
  30957. Object.defineProperty(Material, "LineStripDrawMode", {
  30958. /**
  30959. * Returns the line strip draw mode.
  30960. */
  30961. get: function () {
  30962. return Material._LineStripDrawMode;
  30963. },
  30964. enumerable: true,
  30965. configurable: true
  30966. });
  30967. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30968. /**
  30969. * Returns the triangle strip draw mode.
  30970. */
  30971. get: function () {
  30972. return Material._TriangleStripDrawMode;
  30973. },
  30974. enumerable: true,
  30975. configurable: true
  30976. });
  30977. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30978. /**
  30979. * Returns the triangle fan draw mode.
  30980. */
  30981. get: function () {
  30982. return Material._TriangleFanDrawMode;
  30983. },
  30984. enumerable: true,
  30985. configurable: true
  30986. });
  30987. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30988. /**
  30989. * Returns the clock-wise side orientation.
  30990. */
  30991. get: function () {
  30992. return Material._ClockWiseSideOrientation;
  30993. },
  30994. enumerable: true,
  30995. configurable: true
  30996. });
  30997. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30998. /**
  30999. * Returns the counter clock-wise side orientation.
  31000. */
  31001. get: function () {
  31002. return Material._CounterClockWiseSideOrientation;
  31003. },
  31004. enumerable: true,
  31005. configurable: true
  31006. });
  31007. Object.defineProperty(Material, "TextureDirtyFlag", {
  31008. /**
  31009. * Returns the dirty texture flag value.
  31010. */
  31011. get: function () {
  31012. return Material._TextureDirtyFlag;
  31013. },
  31014. enumerable: true,
  31015. configurable: true
  31016. });
  31017. Object.defineProperty(Material, "LightDirtyFlag", {
  31018. /**
  31019. * Returns the dirty light flag value.
  31020. */
  31021. get: function () {
  31022. return Material._LightDirtyFlag;
  31023. },
  31024. enumerable: true,
  31025. configurable: true
  31026. });
  31027. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31028. /**
  31029. * Returns the dirty fresnel flag value.
  31030. */
  31031. get: function () {
  31032. return Material._FresnelDirtyFlag;
  31033. },
  31034. enumerable: true,
  31035. configurable: true
  31036. });
  31037. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31038. /**
  31039. * Returns the dirty attributes flag value.
  31040. */
  31041. get: function () {
  31042. return Material._AttributesDirtyFlag;
  31043. },
  31044. enumerable: true,
  31045. configurable: true
  31046. });
  31047. Object.defineProperty(Material, "MiscDirtyFlag", {
  31048. /**
  31049. * Returns the dirty misc flag value.
  31050. */
  31051. get: function () {
  31052. return Material._MiscDirtyFlag;
  31053. },
  31054. enumerable: true,
  31055. configurable: true
  31056. });
  31057. Object.defineProperty(Material.prototype, "alpha", {
  31058. /**
  31059. * Gets the alpha value of the material.
  31060. */
  31061. get: function () {
  31062. return this._alpha;
  31063. },
  31064. /**
  31065. * Sets the alpha value of the material.
  31066. */
  31067. set: function (value) {
  31068. if (this._alpha === value) {
  31069. return;
  31070. }
  31071. this._alpha = value;
  31072. this.markAsDirty(Material.MiscDirtyFlag);
  31073. },
  31074. enumerable: true,
  31075. configurable: true
  31076. });
  31077. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31078. /**
  31079. * Gets the back-face culling state.
  31080. */
  31081. get: function () {
  31082. return this._backFaceCulling;
  31083. },
  31084. /**
  31085. * Sets the back-face culling state.
  31086. */
  31087. set: function (value) {
  31088. if (this._backFaceCulling === value) {
  31089. return;
  31090. }
  31091. this._backFaceCulling = value;
  31092. this.markAsDirty(Material.TextureDirtyFlag);
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. Object.defineProperty(Material.prototype, "onDispose", {
  31098. /**
  31099. * Called during a dispose event.
  31100. */
  31101. set: function (callback) {
  31102. if (this._onDisposeObserver) {
  31103. this.onDisposeObservable.remove(this._onDisposeObserver);
  31104. }
  31105. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31106. },
  31107. enumerable: true,
  31108. configurable: true
  31109. });
  31110. Object.defineProperty(Material.prototype, "onBind", {
  31111. /**
  31112. * Called during a bind event.
  31113. */
  31114. set: function (callback) {
  31115. if (this._onBindObserver) {
  31116. this.onBindObservable.remove(this._onBindObserver);
  31117. }
  31118. this._onBindObserver = this.onBindObservable.add(callback);
  31119. },
  31120. enumerable: true,
  31121. configurable: true
  31122. });
  31123. Object.defineProperty(Material.prototype, "alphaMode", {
  31124. /**
  31125. * Gets the value of the alpha mode.
  31126. */
  31127. get: function () {
  31128. return this._alphaMode;
  31129. },
  31130. /**
  31131. * Sets the value of the alpha mode.
  31132. */
  31133. set: function (value) {
  31134. if (this._alphaMode === value) {
  31135. return;
  31136. }
  31137. this._alphaMode = value;
  31138. this.markAsDirty(Material.TextureDirtyFlag);
  31139. },
  31140. enumerable: true,
  31141. configurable: true
  31142. });
  31143. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31144. /**
  31145. * Gets the depth pre-pass value.
  31146. */
  31147. get: function () {
  31148. return this._needDepthPrePass;
  31149. },
  31150. /**
  31151. * Sets the need depth pre-pass value.
  31152. */
  31153. set: function (value) {
  31154. if (this._needDepthPrePass === value) {
  31155. return;
  31156. }
  31157. this._needDepthPrePass = value;
  31158. if (this._needDepthPrePass) {
  31159. this.checkReadyOnEveryCall = true;
  31160. }
  31161. },
  31162. enumerable: true,
  31163. configurable: true
  31164. });
  31165. Object.defineProperty(Material.prototype, "fogEnabled", {
  31166. /**
  31167. * Gets the value of the fog enabled state.
  31168. */
  31169. get: function () {
  31170. return this._fogEnabled;
  31171. },
  31172. /**
  31173. * Sets the state for enabling fog.
  31174. */
  31175. set: function (value) {
  31176. if (this._fogEnabled === value) {
  31177. return;
  31178. }
  31179. this._fogEnabled = value;
  31180. this.markAsDirty(Material.MiscDirtyFlag);
  31181. },
  31182. enumerable: true,
  31183. configurable: true
  31184. });
  31185. Object.defineProperty(Material.prototype, "wireframe", {
  31186. /**
  31187. * Gets a value specifying if wireframe mode is enabled.
  31188. */
  31189. get: function () {
  31190. return this._fillMode === Material.WireFrameFillMode;
  31191. },
  31192. /**
  31193. * Sets the state of wireframe mode.
  31194. */
  31195. set: function (value) {
  31196. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31197. },
  31198. enumerable: true,
  31199. configurable: true
  31200. });
  31201. Object.defineProperty(Material.prototype, "pointsCloud", {
  31202. /**
  31203. * Gets the value specifying if point clouds are enabled.
  31204. */
  31205. get: function () {
  31206. return this._fillMode === Material.PointFillMode;
  31207. },
  31208. /**
  31209. * Sets the state of point cloud mode.
  31210. */
  31211. set: function (value) {
  31212. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31213. },
  31214. enumerable: true,
  31215. configurable: true
  31216. });
  31217. Object.defineProperty(Material.prototype, "fillMode", {
  31218. /**
  31219. * Gets the material fill mode.
  31220. */
  31221. get: function () {
  31222. return this._fillMode;
  31223. },
  31224. /**
  31225. * Sets the material fill mode.
  31226. */
  31227. set: function (value) {
  31228. if (this._fillMode === value) {
  31229. return;
  31230. }
  31231. this._fillMode = value;
  31232. this.markAsDirty(Material.MiscDirtyFlag);
  31233. },
  31234. enumerable: true,
  31235. configurable: true
  31236. });
  31237. /**
  31238. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31239. * subclasses should override adding information pertainent to themselves.
  31240. * @returns - String with material information.
  31241. */
  31242. Material.prototype.toString = function (fullDetails) {
  31243. var ret = "Name: " + this.name;
  31244. if (fullDetails) {
  31245. }
  31246. return ret;
  31247. };
  31248. /**
  31249. * Gets the class name of the material.
  31250. * @returns - String with the class name of the material.
  31251. */
  31252. Material.prototype.getClassName = function () {
  31253. return "Material";
  31254. };
  31255. Object.defineProperty(Material.prototype, "isFrozen", {
  31256. /**
  31257. * Specifies if updates for the material been locked.
  31258. */
  31259. get: function () {
  31260. return this.checkReadyOnlyOnce;
  31261. },
  31262. enumerable: true,
  31263. configurable: true
  31264. });
  31265. /**
  31266. * Locks updates for the material.
  31267. */
  31268. Material.prototype.freeze = function () {
  31269. this.checkReadyOnlyOnce = true;
  31270. };
  31271. /**
  31272. * Unlocks updates for the material.
  31273. */
  31274. Material.prototype.unfreeze = function () {
  31275. this.checkReadyOnlyOnce = false;
  31276. };
  31277. /**
  31278. * Specifies if the material is ready to be used.
  31279. * @param mesh - BJS mesh.
  31280. * @param useInstances - Specifies if instances should be used.
  31281. * @returns - Boolean indicating if the material is ready to be used.
  31282. */
  31283. Material.prototype.isReady = function (mesh, useInstances) {
  31284. return true;
  31285. };
  31286. /**
  31287. * Specifies that the submesh is ready to be used.
  31288. * @param mesh - BJS mesh.
  31289. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31290. * @param useInstances - Specifies that instances should be used.
  31291. * @returns - boolean indicating that the submesh is ready or not.
  31292. */
  31293. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31294. return false;
  31295. };
  31296. /**
  31297. * Returns the material effect.
  31298. * @returns - Nullable material effect.
  31299. */
  31300. Material.prototype.getEffect = function () {
  31301. return this._effect;
  31302. };
  31303. /**
  31304. * Returns the BJS scene.
  31305. * @returns - BJS Scene.
  31306. */
  31307. Material.prototype.getScene = function () {
  31308. return this._scene;
  31309. };
  31310. /**
  31311. * Specifies if the material will require alpha blending
  31312. * @returns - Boolean specifying if alpha blending is needed.
  31313. */
  31314. Material.prototype.needAlphaBlending = function () {
  31315. return (this.alpha < 1.0);
  31316. };
  31317. /**
  31318. * Specifies if the mesh will require alpha blending.
  31319. * @param mesh - BJS mesh.
  31320. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31321. */
  31322. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31323. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31324. };
  31325. /**
  31326. * Specifies if this material should be rendered in alpha test mode.
  31327. * @returns - Boolean specifying if an alpha test is needed.
  31328. */
  31329. Material.prototype.needAlphaTesting = function () {
  31330. return false;
  31331. };
  31332. /**
  31333. * Gets the texture used for the alpha test.
  31334. * @returns - Nullable alpha test texture.
  31335. */
  31336. Material.prototype.getAlphaTestTexture = function () {
  31337. return null;
  31338. };
  31339. /**
  31340. * Marks the material to indicate that it needs to be re-calculated.
  31341. */
  31342. Material.prototype.markDirty = function () {
  31343. this._wasPreviouslyReady = false;
  31344. };
  31345. Material.prototype._preBind = function (effect, overrideOrientation) {
  31346. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31347. var engine = this._scene.getEngine();
  31348. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31349. var reverse = orientation === Material.ClockWiseSideOrientation;
  31350. engine.enableEffect(effect ? effect : this._effect);
  31351. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31352. return reverse;
  31353. };
  31354. /**
  31355. * Binds the material to the mesh.
  31356. * @param world - World transformation matrix.
  31357. * @param mesh - Mesh to bind the material to.
  31358. */
  31359. Material.prototype.bind = function (world, mesh) {
  31360. };
  31361. /**
  31362. * Binds the submesh to the material.
  31363. * @param world - World transformation matrix.
  31364. * @param mesh - Mesh containing the submesh.
  31365. * @param subMesh - Submesh to bind the material to.
  31366. */
  31367. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31368. };
  31369. /**
  31370. * Binds the world matrix to the material.
  31371. * @param world - World transformation matrix.
  31372. */
  31373. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31374. };
  31375. /**
  31376. * Binds the scene's uniform buffer to the effect.
  31377. * @param effect - Effect to bind to the scene uniform buffer.
  31378. * @param sceneUbo - Scene uniform buffer.
  31379. */
  31380. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31381. sceneUbo.bindToEffect(effect, "Scene");
  31382. };
  31383. /**
  31384. * Binds the view matrix to the effect.
  31385. * @param effect - Effect to bind the view matrix to.
  31386. */
  31387. Material.prototype.bindView = function (effect) {
  31388. if (!this._useUBO) {
  31389. effect.setMatrix("view", this.getScene().getViewMatrix());
  31390. }
  31391. else {
  31392. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31393. }
  31394. };
  31395. /**
  31396. * Binds the view projection matrix to the effect.
  31397. * @param effect - Effect to bind the view projection matrix to.
  31398. */
  31399. Material.prototype.bindViewProjection = function (effect) {
  31400. if (!this._useUBO) {
  31401. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31402. }
  31403. else {
  31404. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31405. }
  31406. };
  31407. /**
  31408. * Specifies if material alpha testing should be turned on for the mesh.
  31409. * @param mesh - BJS mesh.
  31410. */
  31411. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31412. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31413. };
  31414. /**
  31415. * Processes to execute after binding the material to a mesh.
  31416. * @param mesh - BJS mesh.
  31417. */
  31418. Material.prototype._afterBind = function (mesh) {
  31419. this._scene._cachedMaterial = this;
  31420. if (mesh) {
  31421. this._scene._cachedVisibility = mesh.visibility;
  31422. }
  31423. else {
  31424. this._scene._cachedVisibility = 1;
  31425. }
  31426. if (mesh) {
  31427. this.onBindObservable.notifyObservers(mesh);
  31428. }
  31429. if (this.disableDepthWrite) {
  31430. var engine = this._scene.getEngine();
  31431. this._cachedDepthWriteState = engine.getDepthWrite();
  31432. engine.setDepthWrite(false);
  31433. }
  31434. };
  31435. /**
  31436. * Unbinds the material from the mesh.
  31437. */
  31438. Material.prototype.unbind = function () {
  31439. this.onUnBindObservable.notifyObservers(this);
  31440. if (this.disableDepthWrite) {
  31441. var engine = this._scene.getEngine();
  31442. engine.setDepthWrite(this._cachedDepthWriteState);
  31443. }
  31444. };
  31445. /**
  31446. * Gets the active textures from the material.
  31447. * @returns - Array of textures.
  31448. */
  31449. Material.prototype.getActiveTextures = function () {
  31450. return [];
  31451. };
  31452. /**
  31453. * Specifies if the material uses a texture.
  31454. * @param texture - Texture to check against the material.
  31455. * @returns - Boolean specifying if the material uses the texture.
  31456. */
  31457. Material.prototype.hasTexture = function (texture) {
  31458. return false;
  31459. };
  31460. /**
  31461. * Makes a duplicate of the material, and gives it a new name.
  31462. * @param name - Name to call the duplicated material.
  31463. * @returns - Nullable cloned material
  31464. */
  31465. Material.prototype.clone = function (name) {
  31466. return null;
  31467. };
  31468. /**
  31469. * Gets the meshes bound to the material.
  31470. * @returns - Array of meshes bound to the material.
  31471. */
  31472. Material.prototype.getBindedMeshes = function () {
  31473. var result = new Array();
  31474. for (var index = 0; index < this._scene.meshes.length; index++) {
  31475. var mesh = this._scene.meshes[index];
  31476. if (mesh.material === this) {
  31477. result.push(mesh);
  31478. }
  31479. }
  31480. return result;
  31481. };
  31482. /**
  31483. * Force shader compilation
  31484. * @param mesh - BJS mesh.
  31485. * @param onCompiled - function to execute once the material is compiled.
  31486. * @param options - options to pass to this function.
  31487. */
  31488. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31489. var _this = this;
  31490. var localOptions = __assign({ clipPlane: false }, options);
  31491. var subMesh = new BABYLON.BaseSubMesh();
  31492. var scene = this.getScene();
  31493. var checkReady = function () {
  31494. if (!_this._scene || !_this._scene.getEngine()) {
  31495. return;
  31496. }
  31497. if (subMesh._materialDefines) {
  31498. subMesh._materialDefines._renderId = -1;
  31499. }
  31500. var clipPlaneState = scene.clipPlane;
  31501. if (localOptions.clipPlane) {
  31502. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31503. }
  31504. if (_this.storeEffectOnSubMeshes) {
  31505. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31506. if (onCompiled) {
  31507. onCompiled(_this);
  31508. }
  31509. }
  31510. else {
  31511. setTimeout(checkReady, 16);
  31512. }
  31513. }
  31514. else {
  31515. if (_this.isReady(mesh)) {
  31516. if (onCompiled) {
  31517. onCompiled(_this);
  31518. }
  31519. }
  31520. else {
  31521. setTimeout(checkReady, 16);
  31522. }
  31523. }
  31524. if (localOptions.clipPlane) {
  31525. scene.clipPlane = clipPlaneState;
  31526. }
  31527. };
  31528. checkReady();
  31529. };
  31530. /**
  31531. * Force shader compilation.
  31532. * @param mesh The mesh that will use this material
  31533. * @param options Additional options for compiling the shaders
  31534. * @returns A promise that resolves when the compilation completes
  31535. */
  31536. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31537. var _this = this;
  31538. return new Promise(function (resolve) {
  31539. _this.forceCompilation(mesh, function () {
  31540. resolve();
  31541. }, options);
  31542. });
  31543. };
  31544. /**
  31545. * Marks a define in the material to indicate that it needs to be re-computed.
  31546. * @param flag - Material define flag.
  31547. */
  31548. Material.prototype.markAsDirty = function (flag) {
  31549. if (flag & Material.TextureDirtyFlag) {
  31550. this._markAllSubMeshesAsTexturesDirty();
  31551. }
  31552. if (flag & Material.LightDirtyFlag) {
  31553. this._markAllSubMeshesAsLightsDirty();
  31554. }
  31555. if (flag & Material.FresnelDirtyFlag) {
  31556. this._markAllSubMeshesAsFresnelDirty();
  31557. }
  31558. if (flag & Material.AttributesDirtyFlag) {
  31559. this._markAllSubMeshesAsAttributesDirty();
  31560. }
  31561. if (flag & Material.MiscDirtyFlag) {
  31562. this._markAllSubMeshesAsMiscDirty();
  31563. }
  31564. this.getScene().resetCachedMaterial();
  31565. };
  31566. /**
  31567. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31568. * @param func - function which checks material defines against the submeshes.
  31569. */
  31570. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31571. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31572. var mesh = _a[_i];
  31573. if (!mesh.subMeshes) {
  31574. continue;
  31575. }
  31576. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31577. var subMesh = _c[_b];
  31578. if (subMesh.getMaterial() !== this) {
  31579. continue;
  31580. }
  31581. if (!subMesh._materialDefines) {
  31582. continue;
  31583. }
  31584. func(subMesh._materialDefines);
  31585. }
  31586. }
  31587. };
  31588. /**
  31589. * Indicates that image processing needs to be re-calculated for all submeshes.
  31590. */
  31591. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31592. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31593. };
  31594. /**
  31595. * Indicates that textures need to be re-calculated for all submeshes.
  31596. */
  31597. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31598. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31599. };
  31600. /**
  31601. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31602. */
  31603. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31604. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31605. };
  31606. /**
  31607. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31608. */
  31609. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31610. this._markAllSubMeshesAsDirty(function (defines) {
  31611. defines.markAsFresnelDirty();
  31612. defines.markAsMiscDirty();
  31613. });
  31614. };
  31615. /**
  31616. * Indicates that lights need to be re-calculated for all submeshes.
  31617. */
  31618. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31619. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31620. };
  31621. /**
  31622. * Indicates that attributes need to be re-calculated for all submeshes.
  31623. */
  31624. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31625. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31626. };
  31627. /**
  31628. * Indicates that misc needs to be re-calculated for all submeshes.
  31629. */
  31630. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31631. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31632. };
  31633. /**
  31634. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31635. */
  31636. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31637. this._markAllSubMeshesAsDirty(function (defines) {
  31638. defines.markAsTexturesDirty();
  31639. defines.markAsMiscDirty();
  31640. });
  31641. };
  31642. /**
  31643. * Disposes the material.
  31644. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31645. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31646. */
  31647. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31648. // Animations
  31649. this.getScene().stopAnimation(this);
  31650. // Remove from scene
  31651. var index = this._scene.materials.indexOf(this);
  31652. if (index >= 0) {
  31653. this._scene.materials.splice(index, 1);
  31654. }
  31655. // Remove from meshes
  31656. for (index = 0; index < this._scene.meshes.length; index++) {
  31657. var mesh = this._scene.meshes[index];
  31658. if (mesh.material === this) {
  31659. mesh.material = null;
  31660. if (mesh.geometry) {
  31661. var geometry = (mesh.geometry);
  31662. if (this.storeEffectOnSubMeshes) {
  31663. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31664. var subMesh = _a[_i];
  31665. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31666. if (forceDisposeEffect && subMesh._materialEffect) {
  31667. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31668. }
  31669. }
  31670. }
  31671. else {
  31672. geometry._releaseVertexArrayObject(this._effect);
  31673. }
  31674. }
  31675. }
  31676. }
  31677. this._uniformBuffer.dispose();
  31678. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31679. if (forceDisposeEffect && this._effect) {
  31680. if (!this.storeEffectOnSubMeshes) {
  31681. this._scene.getEngine()._releaseEffect(this._effect);
  31682. }
  31683. this._effect = null;
  31684. }
  31685. // Callback
  31686. this.onDisposeObservable.notifyObservers(this);
  31687. this.onDisposeObservable.clear();
  31688. this.onBindObservable.clear();
  31689. this.onUnBindObservable.clear();
  31690. };
  31691. /**
  31692. * Serializes this material.
  31693. * @returns - serialized material object.
  31694. */
  31695. Material.prototype.serialize = function () {
  31696. return BABYLON.SerializationHelper.Serialize(this);
  31697. };
  31698. /**
  31699. * Creates a MultiMaterial from parse MultiMaterial data.
  31700. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31701. * @param scene - BJS scene.
  31702. * @returns - MultiMaterial.
  31703. */
  31704. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31705. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31706. multiMaterial.id = parsedMultiMaterial.id;
  31707. if (BABYLON.Tags) {
  31708. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31709. }
  31710. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31711. var subMatId = parsedMultiMaterial.materials[matIndex];
  31712. if (subMatId) {
  31713. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31714. }
  31715. else {
  31716. multiMaterial.subMaterials.push(null);
  31717. }
  31718. }
  31719. return multiMaterial;
  31720. };
  31721. /**
  31722. * Creates a material from parsed material data.
  31723. * @param parsedMaterial - Parsed material data.
  31724. * @param scene - BJS scene.
  31725. * @param rootUrl - Root URL containing the material information.
  31726. * @returns - Parsed material.
  31727. */
  31728. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31729. if (!parsedMaterial.customType) {
  31730. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31731. }
  31732. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31733. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31734. if (!BABYLON.LegacyPBRMaterial) {
  31735. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31736. return;
  31737. }
  31738. }
  31739. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31740. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31741. ;
  31742. };
  31743. // Triangle views
  31744. Material._TriangleFillMode = 0;
  31745. Material._WireFrameFillMode = 1;
  31746. Material._PointFillMode = 2;
  31747. // Draw modes
  31748. Material._PointListDrawMode = 3;
  31749. Material._LineListDrawMode = 4;
  31750. Material._LineLoopDrawMode = 5;
  31751. Material._LineStripDrawMode = 6;
  31752. Material._TriangleStripDrawMode = 7;
  31753. Material._TriangleFanDrawMode = 8;
  31754. /**
  31755. * Stores the clock-wise side orientation.
  31756. */
  31757. Material._ClockWiseSideOrientation = 0;
  31758. /**
  31759. * Stores the counter clock-wise side orientation.
  31760. */
  31761. Material._CounterClockWiseSideOrientation = 1;
  31762. /**
  31763. * The dirty texture flag value.
  31764. */
  31765. Material._TextureDirtyFlag = 1;
  31766. /**
  31767. * The dirty light flag value.
  31768. */
  31769. Material._LightDirtyFlag = 2;
  31770. /**
  31771. * The dirty fresnel flag value.
  31772. */
  31773. Material._FresnelDirtyFlag = 4;
  31774. /**
  31775. * The dirty attribute flag value.
  31776. */
  31777. Material._AttributesDirtyFlag = 8;
  31778. /**
  31779. * The dirty misc flag value.
  31780. */
  31781. Material._MiscDirtyFlag = 16;
  31782. __decorate([
  31783. BABYLON.serialize()
  31784. ], Material.prototype, "id", void 0);
  31785. __decorate([
  31786. BABYLON.serialize()
  31787. ], Material.prototype, "name", void 0);
  31788. __decorate([
  31789. BABYLON.serialize()
  31790. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31791. __decorate([
  31792. BABYLON.serialize()
  31793. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31794. __decorate([
  31795. BABYLON.serialize()
  31796. ], Material.prototype, "state", void 0);
  31797. __decorate([
  31798. BABYLON.serialize("alpha")
  31799. ], Material.prototype, "_alpha", void 0);
  31800. __decorate([
  31801. BABYLON.serialize("backFaceCulling")
  31802. ], Material.prototype, "_backFaceCulling", void 0);
  31803. __decorate([
  31804. BABYLON.serialize()
  31805. ], Material.prototype, "sideOrientation", void 0);
  31806. __decorate([
  31807. BABYLON.serialize("alphaMode")
  31808. ], Material.prototype, "_alphaMode", void 0);
  31809. __decorate([
  31810. BABYLON.serialize()
  31811. ], Material.prototype, "_needDepthPrePass", void 0);
  31812. __decorate([
  31813. BABYLON.serialize()
  31814. ], Material.prototype, "disableDepthWrite", void 0);
  31815. __decorate([
  31816. BABYLON.serialize()
  31817. ], Material.prototype, "forceDepthWrite", void 0);
  31818. __decorate([
  31819. BABYLON.serialize()
  31820. ], Material.prototype, "separateCullingPass", void 0);
  31821. __decorate([
  31822. BABYLON.serialize("fogEnabled")
  31823. ], Material.prototype, "_fogEnabled", void 0);
  31824. __decorate([
  31825. BABYLON.serialize()
  31826. ], Material.prototype, "pointSize", void 0);
  31827. __decorate([
  31828. BABYLON.serialize()
  31829. ], Material.prototype, "zOffset", void 0);
  31830. __decorate([
  31831. BABYLON.serialize()
  31832. ], Material.prototype, "wireframe", null);
  31833. __decorate([
  31834. BABYLON.serialize()
  31835. ], Material.prototype, "pointsCloud", null);
  31836. __decorate([
  31837. BABYLON.serialize()
  31838. ], Material.prototype, "fillMode", null);
  31839. return Material;
  31840. }());
  31841. BABYLON.Material = Material;
  31842. })(BABYLON || (BABYLON = {}));
  31843. //# sourceMappingURL=babylon.material.js.map
  31844. var BABYLON;
  31845. (function (BABYLON) {
  31846. var UniformBuffer = /** @class */ (function () {
  31847. /**
  31848. * Uniform buffer objects.
  31849. *
  31850. * Handles blocks of uniform on the GPU.
  31851. *
  31852. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31853. *
  31854. * For more information, please refer to :
  31855. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31856. */
  31857. function UniformBuffer(engine, data, dynamic) {
  31858. this._engine = engine;
  31859. this._noUBO = !engine.supportsUniformBuffers;
  31860. this._dynamic = dynamic;
  31861. this._data = data || [];
  31862. this._uniformLocations = {};
  31863. this._uniformSizes = {};
  31864. this._uniformLocationPointer = 0;
  31865. this._needSync = false;
  31866. if (this._noUBO) {
  31867. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31868. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31869. this.updateFloat = this._updateFloatForEffect;
  31870. this.updateFloat2 = this._updateFloat2ForEffect;
  31871. this.updateFloat3 = this._updateFloat3ForEffect;
  31872. this.updateFloat4 = this._updateFloat4ForEffect;
  31873. this.updateMatrix = this._updateMatrixForEffect;
  31874. this.updateVector3 = this._updateVector3ForEffect;
  31875. this.updateVector4 = this._updateVector4ForEffect;
  31876. this.updateColor3 = this._updateColor3ForEffect;
  31877. this.updateColor4 = this._updateColor4ForEffect;
  31878. }
  31879. else {
  31880. this._engine._uniformBuffers.push(this);
  31881. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31882. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31883. this.updateFloat = this._updateFloatForUniform;
  31884. this.updateFloat2 = this._updateFloat2ForUniform;
  31885. this.updateFloat3 = this._updateFloat3ForUniform;
  31886. this.updateFloat4 = this._updateFloat4ForUniform;
  31887. this.updateMatrix = this._updateMatrixForUniform;
  31888. this.updateVector3 = this._updateVector3ForUniform;
  31889. this.updateVector4 = this._updateVector4ForUniform;
  31890. this.updateColor3 = this._updateColor3ForUniform;
  31891. this.updateColor4 = this._updateColor4ForUniform;
  31892. }
  31893. }
  31894. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31895. // Properties
  31896. /**
  31897. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31898. * or just falling back on setUniformXXX calls.
  31899. */
  31900. get: function () {
  31901. return !this._noUBO;
  31902. },
  31903. enumerable: true,
  31904. configurable: true
  31905. });
  31906. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31907. /**
  31908. * Indicates if the WebGL underlying uniform buffer is in sync
  31909. * with the javascript cache data.
  31910. */
  31911. get: function () {
  31912. return !this._needSync;
  31913. },
  31914. enumerable: true,
  31915. configurable: true
  31916. });
  31917. /**
  31918. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31919. * Also, a dynamic UniformBuffer will disable cache verification and always
  31920. * update the underlying WebGL uniform buffer to the GPU.
  31921. */
  31922. UniformBuffer.prototype.isDynamic = function () {
  31923. return this._dynamic !== undefined;
  31924. };
  31925. /**
  31926. * The data cache on JS side.
  31927. */
  31928. UniformBuffer.prototype.getData = function () {
  31929. return this._bufferData;
  31930. };
  31931. /**
  31932. * The underlying WebGL Uniform buffer.
  31933. */
  31934. UniformBuffer.prototype.getBuffer = function () {
  31935. return this._buffer;
  31936. };
  31937. /**
  31938. * std140 layout specifies how to align data within an UBO structure.
  31939. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31940. * for specs.
  31941. */
  31942. UniformBuffer.prototype._fillAlignment = function (size) {
  31943. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31944. // and 4x4 matrices
  31945. // TODO : change if other types are used
  31946. var alignment;
  31947. if (size <= 2) {
  31948. alignment = size;
  31949. }
  31950. else {
  31951. alignment = 4;
  31952. }
  31953. if ((this._uniformLocationPointer % alignment) !== 0) {
  31954. var oldPointer = this._uniformLocationPointer;
  31955. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31956. var diff = this._uniformLocationPointer - oldPointer;
  31957. for (var i = 0; i < diff; i++) {
  31958. this._data.push(0);
  31959. }
  31960. }
  31961. };
  31962. /**
  31963. * Adds an uniform in the buffer.
  31964. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31965. * for the layout to be correct !
  31966. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31967. * @param {number|number[]} size Data size, or data directly.
  31968. */
  31969. UniformBuffer.prototype.addUniform = function (name, size) {
  31970. if (this._noUBO) {
  31971. return;
  31972. }
  31973. if (this._uniformLocations[name] !== undefined) {
  31974. // Already existing uniform
  31975. return;
  31976. }
  31977. // This function must be called in the order of the shader layout !
  31978. // size can be the size of the uniform, or data directly
  31979. var data;
  31980. if (size instanceof Array) {
  31981. data = size;
  31982. size = data.length;
  31983. }
  31984. else {
  31985. size = size;
  31986. data = [];
  31987. // Fill with zeros
  31988. for (var i = 0; i < size; i++) {
  31989. data.push(0);
  31990. }
  31991. }
  31992. this._fillAlignment(size);
  31993. this._uniformSizes[name] = size;
  31994. this._uniformLocations[name] = this._uniformLocationPointer;
  31995. this._uniformLocationPointer += size;
  31996. for (var i = 0; i < size; i++) {
  31997. this._data.push(data[i]);
  31998. }
  31999. this._needSync = true;
  32000. };
  32001. /**
  32002. * Wrapper for addUniform.
  32003. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32004. * @param {Matrix} mat A 4x4 matrix.
  32005. */
  32006. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32007. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32008. };
  32009. /**
  32010. * Wrapper for addUniform.
  32011. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32012. * @param {number} x
  32013. * @param {number} y
  32014. */
  32015. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32016. var temp = [x, y];
  32017. this.addUniform(name, temp);
  32018. };
  32019. /**
  32020. * Wrapper for addUniform.
  32021. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32022. * @param {number} x
  32023. * @param {number} y
  32024. * @param {number} z
  32025. */
  32026. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32027. var temp = [x, y, z];
  32028. this.addUniform(name, temp);
  32029. };
  32030. /**
  32031. * Wrapper for addUniform.
  32032. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32033. * @param {Color3} color
  32034. */
  32035. UniformBuffer.prototype.addColor3 = function (name, color) {
  32036. var temp = new Array();
  32037. color.toArray(temp);
  32038. this.addUniform(name, temp);
  32039. };
  32040. /**
  32041. * Wrapper for addUniform.
  32042. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32043. * @param {Color3} color
  32044. * @param {number} alpha
  32045. */
  32046. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32047. var temp = new Array();
  32048. color.toArray(temp);
  32049. temp.push(alpha);
  32050. this.addUniform(name, temp);
  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 {Vector3} vector
  32056. */
  32057. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32058. var temp = new Array();
  32059. vector.toArray(temp);
  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. */
  32066. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32067. this.addUniform(name, 12);
  32068. };
  32069. /**
  32070. * Wrapper for addUniform.
  32071. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32072. */
  32073. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32074. this.addUniform(name, 8);
  32075. };
  32076. /**
  32077. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32078. */
  32079. UniformBuffer.prototype.create = function () {
  32080. if (this._noUBO) {
  32081. return;
  32082. }
  32083. if (this._buffer) {
  32084. return; // nothing to do
  32085. }
  32086. // See spec, alignment must be filled as a vec4
  32087. this._fillAlignment(4);
  32088. this._bufferData = new Float32Array(this._data);
  32089. this._rebuild();
  32090. this._needSync = true;
  32091. };
  32092. UniformBuffer.prototype._rebuild = function () {
  32093. if (this._noUBO) {
  32094. return;
  32095. }
  32096. if (this._dynamic) {
  32097. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32098. }
  32099. else {
  32100. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32101. }
  32102. };
  32103. /**
  32104. * Updates the WebGL Uniform Buffer on the GPU.
  32105. * If the `dynamic` flag is set to true, no cache comparison is done.
  32106. * Otherwise, the buffer will be updated only if the cache differs.
  32107. */
  32108. UniformBuffer.prototype.update = function () {
  32109. if (!this._buffer) {
  32110. this.create();
  32111. return;
  32112. }
  32113. if (!this._dynamic && !this._needSync) {
  32114. return;
  32115. }
  32116. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32117. this._needSync = false;
  32118. };
  32119. /**
  32120. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32121. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32122. * @param {number[]|Float32Array} data Flattened data
  32123. * @param {number} size Size of the data.
  32124. */
  32125. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32126. var location = this._uniformLocations[uniformName];
  32127. if (location === undefined) {
  32128. if (this._buffer) {
  32129. // Cannot add an uniform if the buffer is already created
  32130. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32131. return;
  32132. }
  32133. this.addUniform(uniformName, size);
  32134. location = this._uniformLocations[uniformName];
  32135. }
  32136. if (!this._buffer) {
  32137. this.create();
  32138. }
  32139. if (!this._dynamic) {
  32140. // Cache for static uniform buffers
  32141. var changed = false;
  32142. for (var i = 0; i < size; i++) {
  32143. if (this._bufferData[location + i] !== data[i]) {
  32144. changed = true;
  32145. this._bufferData[location + i] = data[i];
  32146. }
  32147. }
  32148. this._needSync = this._needSync || changed;
  32149. }
  32150. else {
  32151. // No cache for dynamic
  32152. for (var i = 0; i < size; i++) {
  32153. this._bufferData[location + i] = data[i];
  32154. }
  32155. }
  32156. };
  32157. // Update methods
  32158. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32159. // To match std140, matrix must be realigned
  32160. for (var i = 0; i < 3; i++) {
  32161. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32162. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32163. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32164. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32165. }
  32166. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32167. };
  32168. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32169. this._currentEffect.setMatrix3x3(name, matrix);
  32170. };
  32171. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32172. this._currentEffect.setMatrix2x2(name, matrix);
  32173. };
  32174. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32175. // To match std140, matrix must be realigned
  32176. for (var i = 0; i < 2; i++) {
  32177. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32178. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32179. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32180. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32181. }
  32182. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32183. };
  32184. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32185. this._currentEffect.setFloat(name, x);
  32186. };
  32187. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32188. UniformBuffer._tempBuffer[0] = x;
  32189. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32190. };
  32191. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32192. if (suffix === void 0) { suffix = ""; }
  32193. this._currentEffect.setFloat2(name + suffix, x, y);
  32194. };
  32195. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32196. if (suffix === void 0) { suffix = ""; }
  32197. UniformBuffer._tempBuffer[0] = x;
  32198. UniformBuffer._tempBuffer[1] = y;
  32199. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32200. };
  32201. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32202. if (suffix === void 0) { suffix = ""; }
  32203. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32204. };
  32205. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32206. if (suffix === void 0) { suffix = ""; }
  32207. UniformBuffer._tempBuffer[0] = x;
  32208. UniformBuffer._tempBuffer[1] = y;
  32209. UniformBuffer._tempBuffer[2] = z;
  32210. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32211. };
  32212. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32213. if (suffix === void 0) { suffix = ""; }
  32214. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32215. };
  32216. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32217. if (suffix === void 0) { suffix = ""; }
  32218. UniformBuffer._tempBuffer[0] = x;
  32219. UniformBuffer._tempBuffer[1] = y;
  32220. UniformBuffer._tempBuffer[2] = z;
  32221. UniformBuffer._tempBuffer[3] = w;
  32222. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32223. };
  32224. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32225. this._currentEffect.setMatrix(name, mat);
  32226. };
  32227. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32228. this.updateUniform(name, mat.toArray(), 16);
  32229. };
  32230. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32231. this._currentEffect.setVector3(name, vector);
  32232. };
  32233. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32234. vector.toArray(UniformBuffer._tempBuffer);
  32235. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32236. };
  32237. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32238. this._currentEffect.setVector4(name, vector);
  32239. };
  32240. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32241. vector.toArray(UniformBuffer._tempBuffer);
  32242. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32243. };
  32244. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32245. if (suffix === void 0) { suffix = ""; }
  32246. this._currentEffect.setColor3(name + suffix, color);
  32247. };
  32248. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32249. if (suffix === void 0) { suffix = ""; }
  32250. color.toArray(UniformBuffer._tempBuffer);
  32251. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32252. };
  32253. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32254. if (suffix === void 0) { suffix = ""; }
  32255. this._currentEffect.setColor4(name + suffix, color, alpha);
  32256. };
  32257. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32258. if (suffix === void 0) { suffix = ""; }
  32259. color.toArray(UniformBuffer._tempBuffer);
  32260. UniformBuffer._tempBuffer[3] = alpha;
  32261. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32262. };
  32263. /**
  32264. * Sets a sampler uniform on the effect.
  32265. * @param {string} name Name of the sampler.
  32266. * @param {Texture} texture
  32267. */
  32268. UniformBuffer.prototype.setTexture = function (name, texture) {
  32269. this._currentEffect.setTexture(name, texture);
  32270. };
  32271. /**
  32272. * Directly updates the value of the uniform in the cache AND on the GPU.
  32273. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32274. * @param {number[]|Float32Array} data Flattened data
  32275. */
  32276. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32277. this.updateUniform(uniformName, data, data.length);
  32278. this.update();
  32279. };
  32280. /**
  32281. * Binds this uniform buffer to an effect.
  32282. * @param {Effect} effect
  32283. * @param {string} name Name of the uniform block in the shader.
  32284. */
  32285. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32286. this._currentEffect = effect;
  32287. if (this._noUBO || !this._buffer) {
  32288. return;
  32289. }
  32290. effect.bindUniformBuffer(this._buffer, name);
  32291. };
  32292. /**
  32293. * Disposes the uniform buffer.
  32294. */
  32295. UniformBuffer.prototype.dispose = function () {
  32296. if (this._noUBO) {
  32297. return;
  32298. }
  32299. var index = this._engine._uniformBuffers.indexOf(this);
  32300. if (index !== -1) {
  32301. this._engine._uniformBuffers.splice(index, 1);
  32302. }
  32303. if (!this._buffer) {
  32304. return;
  32305. }
  32306. if (this._engine._releaseBuffer(this._buffer)) {
  32307. this._buffer = null;
  32308. }
  32309. };
  32310. // Pool for avoiding memory leaks
  32311. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32312. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32313. return UniformBuffer;
  32314. }());
  32315. BABYLON.UniformBuffer = UniformBuffer;
  32316. })(BABYLON || (BABYLON = {}));
  32317. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32318. var BABYLON;
  32319. (function (BABYLON) {
  32320. var VertexData = /** @class */ (function () {
  32321. function VertexData() {
  32322. }
  32323. VertexData.prototype.set = function (data, kind) {
  32324. switch (kind) {
  32325. case BABYLON.VertexBuffer.PositionKind:
  32326. this.positions = data;
  32327. break;
  32328. case BABYLON.VertexBuffer.NormalKind:
  32329. this.normals = data;
  32330. break;
  32331. case BABYLON.VertexBuffer.TangentKind:
  32332. this.tangents = data;
  32333. break;
  32334. case BABYLON.VertexBuffer.UVKind:
  32335. this.uvs = data;
  32336. break;
  32337. case BABYLON.VertexBuffer.UV2Kind:
  32338. this.uvs2 = data;
  32339. break;
  32340. case BABYLON.VertexBuffer.UV3Kind:
  32341. this.uvs3 = data;
  32342. break;
  32343. case BABYLON.VertexBuffer.UV4Kind:
  32344. this.uvs4 = data;
  32345. break;
  32346. case BABYLON.VertexBuffer.UV5Kind:
  32347. this.uvs5 = data;
  32348. break;
  32349. case BABYLON.VertexBuffer.UV6Kind:
  32350. this.uvs6 = data;
  32351. break;
  32352. case BABYLON.VertexBuffer.ColorKind:
  32353. this.colors = data;
  32354. break;
  32355. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32356. this.matricesIndices = data;
  32357. break;
  32358. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32359. this.matricesWeights = data;
  32360. break;
  32361. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32362. this.matricesIndicesExtra = data;
  32363. break;
  32364. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32365. this.matricesWeightsExtra = data;
  32366. break;
  32367. }
  32368. };
  32369. /**
  32370. * Associates the vertexData to the passed Mesh.
  32371. * Sets it as updatable or not (default `false`).
  32372. * Returns the VertexData.
  32373. */
  32374. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32375. this._applyTo(mesh, updatable);
  32376. return this;
  32377. };
  32378. /**
  32379. * Associates the vertexData to the passed Geometry.
  32380. * Sets it as updatable or not (default `false`).
  32381. * Returns the VertexData.
  32382. */
  32383. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32384. this._applyTo(geometry, updatable);
  32385. return this;
  32386. };
  32387. /**
  32388. * Updates the associated mesh.
  32389. * Returns the VertexData.
  32390. */
  32391. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32392. this._update(mesh);
  32393. return this;
  32394. };
  32395. /**
  32396. * Updates the associated geometry.
  32397. * Returns the VertexData.
  32398. */
  32399. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32400. this._update(geometry);
  32401. return this;
  32402. };
  32403. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32404. if (updatable === void 0) { updatable = false; }
  32405. if (this.positions) {
  32406. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32407. }
  32408. if (this.normals) {
  32409. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32410. }
  32411. if (this.tangents) {
  32412. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32413. }
  32414. if (this.uvs) {
  32415. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32416. }
  32417. if (this.uvs2) {
  32418. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32419. }
  32420. if (this.uvs3) {
  32421. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32422. }
  32423. if (this.uvs4) {
  32424. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32425. }
  32426. if (this.uvs5) {
  32427. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32428. }
  32429. if (this.uvs6) {
  32430. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32431. }
  32432. if (this.colors) {
  32433. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32434. }
  32435. if (this.matricesIndices) {
  32436. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32437. }
  32438. if (this.matricesWeights) {
  32439. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32440. }
  32441. if (this.matricesIndicesExtra) {
  32442. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32443. }
  32444. if (this.matricesWeightsExtra) {
  32445. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32446. }
  32447. if (this.indices) {
  32448. meshOrGeometry.setIndices(this.indices, null, updatable);
  32449. }
  32450. return this;
  32451. };
  32452. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32453. if (this.positions) {
  32454. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32455. }
  32456. if (this.normals) {
  32457. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32458. }
  32459. if (this.tangents) {
  32460. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32461. }
  32462. if (this.uvs) {
  32463. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32464. }
  32465. if (this.uvs2) {
  32466. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32467. }
  32468. if (this.uvs3) {
  32469. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32470. }
  32471. if (this.uvs4) {
  32472. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32473. }
  32474. if (this.uvs5) {
  32475. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32476. }
  32477. if (this.uvs6) {
  32478. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32479. }
  32480. if (this.colors) {
  32481. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32482. }
  32483. if (this.matricesIndices) {
  32484. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32485. }
  32486. if (this.matricesWeights) {
  32487. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32488. }
  32489. if (this.matricesIndicesExtra) {
  32490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32491. }
  32492. if (this.matricesWeightsExtra) {
  32493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32494. }
  32495. if (this.indices) {
  32496. meshOrGeometry.setIndices(this.indices, null);
  32497. }
  32498. return this;
  32499. };
  32500. /**
  32501. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32502. * Returns the VertexData.
  32503. */
  32504. VertexData.prototype.transform = function (matrix) {
  32505. var transformed = BABYLON.Vector3.Zero();
  32506. var index;
  32507. if (this.positions) {
  32508. var position = BABYLON.Vector3.Zero();
  32509. for (index = 0; index < this.positions.length; index += 3) {
  32510. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32511. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32512. this.positions[index] = transformed.x;
  32513. this.positions[index + 1] = transformed.y;
  32514. this.positions[index + 2] = transformed.z;
  32515. }
  32516. }
  32517. if (this.normals) {
  32518. var normal = BABYLON.Vector3.Zero();
  32519. for (index = 0; index < this.normals.length; index += 3) {
  32520. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32521. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32522. this.normals[index] = transformed.x;
  32523. this.normals[index + 1] = transformed.y;
  32524. this.normals[index + 2] = transformed.z;
  32525. }
  32526. }
  32527. if (this.tangents) {
  32528. var tangent = BABYLON.Vector4.Zero();
  32529. var tangentTransformed = BABYLON.Vector4.Zero();
  32530. for (index = 0; index < this.tangents.length; index += 4) {
  32531. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32532. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32533. this.tangents[index] = tangentTransformed.x;
  32534. this.tangents[index + 1] = tangentTransformed.y;
  32535. this.tangents[index + 2] = tangentTransformed.z;
  32536. this.tangents[index + 3] = tangentTransformed.w;
  32537. }
  32538. }
  32539. return this;
  32540. };
  32541. /**
  32542. * Merges the passed VertexData into the current one.
  32543. * Returns the modified VertexData.
  32544. */
  32545. VertexData.prototype.merge = function (other) {
  32546. this._validate();
  32547. other._validate();
  32548. if (!this.normals !== !other.normals ||
  32549. !this.tangents !== !other.tangents ||
  32550. !this.uvs !== !other.uvs ||
  32551. !this.uvs2 !== !other.uvs2 ||
  32552. !this.uvs3 !== !other.uvs3 ||
  32553. !this.uvs4 !== !other.uvs4 ||
  32554. !this.uvs5 !== !other.uvs5 ||
  32555. !this.uvs6 !== !other.uvs6 ||
  32556. !this.colors !== !other.colors ||
  32557. !this.matricesIndices !== !other.matricesIndices ||
  32558. !this.matricesWeights !== !other.matricesWeights ||
  32559. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32560. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32561. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32562. }
  32563. if (other.indices) {
  32564. if (!this.indices) {
  32565. this.indices = [];
  32566. }
  32567. var offset = this.positions ? this.positions.length / 3 : 0;
  32568. for (var index = 0; index < other.indices.length; index++) {
  32569. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32570. this.indices.push(other.indices[index] + offset);
  32571. }
  32572. }
  32573. this.positions = this._mergeElement(this.positions, other.positions);
  32574. this.normals = this._mergeElement(this.normals, other.normals);
  32575. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32576. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32577. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32578. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32579. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32580. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32581. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32582. this.colors = this._mergeElement(this.colors, other.colors);
  32583. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32584. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32585. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32586. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32587. return this;
  32588. };
  32589. VertexData.prototype._mergeElement = function (source, other) {
  32590. if (!source) {
  32591. return other;
  32592. }
  32593. if (!other) {
  32594. return source;
  32595. }
  32596. var len = other.length + source.length;
  32597. var isSrcTypedArray = source instanceof Float32Array;
  32598. var isOthTypedArray = other instanceof Float32Array;
  32599. // use non-loop method when the source is Float32Array
  32600. if (isSrcTypedArray) {
  32601. var ret32 = new Float32Array(len);
  32602. ret32.set(source);
  32603. ret32.set(other, source.length);
  32604. return ret32;
  32605. // source is number[], when other is also use concat
  32606. }
  32607. else if (!isOthTypedArray) {
  32608. return source.concat(other);
  32609. // source is a number[], but other is a Float32Array, loop required
  32610. }
  32611. else {
  32612. var ret = source.slice(0); // copy source to a separate array
  32613. for (var i = 0, len = other.length; i < len; i++) {
  32614. ret.push(other[i]);
  32615. }
  32616. return ret;
  32617. }
  32618. };
  32619. VertexData.prototype._validate = function () {
  32620. if (!this.positions) {
  32621. throw new Error("Positions are required");
  32622. }
  32623. var getElementCount = function (kind, values) {
  32624. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32625. if ((values.length % stride) !== 0) {
  32626. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32627. }
  32628. return values.length / stride;
  32629. };
  32630. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32631. var validateElementCount = function (kind, values) {
  32632. var elementCount = getElementCount(kind, values);
  32633. if (elementCount !== positionsElementCount) {
  32634. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32635. }
  32636. };
  32637. if (this.normals)
  32638. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32639. if (this.tangents)
  32640. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32641. if (this.uvs)
  32642. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32643. if (this.uvs2)
  32644. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32645. if (this.uvs3)
  32646. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32647. if (this.uvs4)
  32648. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32649. if (this.uvs5)
  32650. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32651. if (this.uvs6)
  32652. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32653. if (this.colors)
  32654. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32655. if (this.matricesIndices)
  32656. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32657. if (this.matricesWeights)
  32658. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32659. if (this.matricesIndicesExtra)
  32660. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32661. if (this.matricesWeightsExtra)
  32662. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32663. };
  32664. /**
  32665. * Serializes the VertexData.
  32666. * Returns a serialized object.
  32667. */
  32668. VertexData.prototype.serialize = function () {
  32669. var serializationObject = this.serialize();
  32670. if (this.positions) {
  32671. serializationObject.positions = this.positions;
  32672. }
  32673. if (this.normals) {
  32674. serializationObject.normals = this.normals;
  32675. }
  32676. if (this.tangents) {
  32677. serializationObject.tangents = this.tangents;
  32678. }
  32679. if (this.uvs) {
  32680. serializationObject.uvs = this.uvs;
  32681. }
  32682. if (this.uvs2) {
  32683. serializationObject.uvs2 = this.uvs2;
  32684. }
  32685. if (this.uvs3) {
  32686. serializationObject.uvs3 = this.uvs3;
  32687. }
  32688. if (this.uvs4) {
  32689. serializationObject.uvs4 = this.uvs4;
  32690. }
  32691. if (this.uvs5) {
  32692. serializationObject.uvs5 = this.uvs5;
  32693. }
  32694. if (this.uvs6) {
  32695. serializationObject.uvs6 = this.uvs6;
  32696. }
  32697. if (this.colors) {
  32698. serializationObject.colors = this.colors;
  32699. }
  32700. if (this.matricesIndices) {
  32701. serializationObject.matricesIndices = this.matricesIndices;
  32702. serializationObject.matricesIndices._isExpanded = true;
  32703. }
  32704. if (this.matricesWeights) {
  32705. serializationObject.matricesWeights = this.matricesWeights;
  32706. }
  32707. if (this.matricesIndicesExtra) {
  32708. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32709. serializationObject.matricesIndicesExtra._isExpanded = true;
  32710. }
  32711. if (this.matricesWeightsExtra) {
  32712. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32713. }
  32714. serializationObject.indices = this.indices;
  32715. return serializationObject;
  32716. };
  32717. // Statics
  32718. /**
  32719. * Returns the object VertexData associated to the passed mesh.
  32720. */
  32721. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32722. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32723. };
  32724. /**
  32725. * Returns the object VertexData associated to the passed geometry.
  32726. */
  32727. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32728. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32729. };
  32730. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32731. var result = new VertexData();
  32732. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32733. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32734. }
  32735. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32736. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32737. }
  32738. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32739. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32740. }
  32741. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32742. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32743. }
  32744. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32745. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32746. }
  32747. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32748. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32749. }
  32750. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32751. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32752. }
  32753. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32754. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32755. }
  32756. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32757. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32758. }
  32759. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32760. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32761. }
  32762. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32763. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32764. }
  32765. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32766. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32767. }
  32768. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32769. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32770. }
  32771. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32772. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32773. }
  32774. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32775. return result;
  32776. };
  32777. /**
  32778. * Creates the vertexData of the Ribbon.
  32779. */
  32780. VertexData.CreateRibbon = function (options) {
  32781. var pathArray = options.pathArray;
  32782. var closeArray = options.closeArray || false;
  32783. var closePath = options.closePath || false;
  32784. var invertUV = options.invertUV || false;
  32785. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32786. var offset = options.offset || defaultOffset;
  32787. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32788. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32789. var customUV = options.uvs;
  32790. var customColors = options.colors;
  32791. var positions = [];
  32792. var indices = [];
  32793. var normals = [];
  32794. var uvs = [];
  32795. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32796. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32797. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32798. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32799. var minlg; // minimal length among all paths from pathArray
  32800. var lg = []; // array of path lengths : nb of vertex per path
  32801. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32802. var p; // path iterator
  32803. var i; // point iterator
  32804. var j; // point iterator
  32805. // if single path in pathArray
  32806. if (pathArray.length < 2) {
  32807. var ar1 = [];
  32808. var ar2 = [];
  32809. for (i = 0; i < pathArray[0].length - offset; i++) {
  32810. ar1.push(pathArray[0][i]);
  32811. ar2.push(pathArray[0][i + offset]);
  32812. }
  32813. pathArray = [ar1, ar2];
  32814. }
  32815. // positions and horizontal distances (u)
  32816. var idc = 0;
  32817. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32818. var path;
  32819. var l;
  32820. minlg = pathArray[0].length;
  32821. var vectlg;
  32822. var dist;
  32823. for (p = 0; p < pathArray.length; p++) {
  32824. uTotalDistance[p] = 0;
  32825. us[p] = [0];
  32826. path = pathArray[p];
  32827. l = path.length;
  32828. minlg = (minlg < l) ? minlg : l;
  32829. j = 0;
  32830. while (j < l) {
  32831. positions.push(path[j].x, path[j].y, path[j].z);
  32832. if (j > 0) {
  32833. vectlg = path[j].subtract(path[j - 1]).length();
  32834. dist = vectlg + uTotalDistance[p];
  32835. us[p].push(dist);
  32836. uTotalDistance[p] = dist;
  32837. }
  32838. j++;
  32839. }
  32840. if (closePath) {
  32841. j--;
  32842. positions.push(path[0].x, path[0].y, path[0].z);
  32843. vectlg = path[j].subtract(path[0]).length();
  32844. dist = vectlg + uTotalDistance[p];
  32845. us[p].push(dist);
  32846. uTotalDistance[p] = dist;
  32847. }
  32848. lg[p] = l + closePathCorr;
  32849. idx[p] = idc;
  32850. idc += (l + closePathCorr);
  32851. }
  32852. // vertical distances (v)
  32853. var path1;
  32854. var path2;
  32855. var vertex1 = null;
  32856. var vertex2 = null;
  32857. for (i = 0; i < minlg + closePathCorr; i++) {
  32858. vTotalDistance[i] = 0;
  32859. vs[i] = [0];
  32860. for (p = 0; p < pathArray.length - 1; p++) {
  32861. path1 = pathArray[p];
  32862. path2 = pathArray[p + 1];
  32863. if (i === minlg) {
  32864. vertex1 = path1[0];
  32865. vertex2 = path2[0];
  32866. }
  32867. else {
  32868. vertex1 = path1[i];
  32869. vertex2 = path2[i];
  32870. }
  32871. vectlg = vertex2.subtract(vertex1).length();
  32872. dist = vectlg + vTotalDistance[i];
  32873. vs[i].push(dist);
  32874. vTotalDistance[i] = dist;
  32875. }
  32876. if (closeArray && vertex2 && vertex1) {
  32877. path1 = pathArray[p];
  32878. path2 = pathArray[0];
  32879. if (i === minlg) {
  32880. vertex2 = path2[0];
  32881. }
  32882. vectlg = vertex2.subtract(vertex1).length();
  32883. dist = vectlg + vTotalDistance[i];
  32884. vTotalDistance[i] = dist;
  32885. }
  32886. }
  32887. // uvs
  32888. var u;
  32889. var v;
  32890. if (customUV) {
  32891. for (p = 0; p < customUV.length; p++) {
  32892. uvs.push(customUV[p].x, customUV[p].y);
  32893. }
  32894. }
  32895. else {
  32896. for (p = 0; p < pathArray.length; p++) {
  32897. for (i = 0; i < minlg + closePathCorr; i++) {
  32898. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32899. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32900. if (invertUV) {
  32901. uvs.push(v, u);
  32902. }
  32903. else {
  32904. uvs.push(u, v);
  32905. }
  32906. }
  32907. }
  32908. }
  32909. // indices
  32910. p = 0; // path index
  32911. var pi = 0; // positions array index
  32912. var l1 = lg[p] - 1; // path1 length
  32913. var l2 = lg[p + 1] - 1; // path2 length
  32914. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32915. var shft = idx[1] - idx[0]; // shift
  32916. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32917. while (pi <= min && p < path1nb) {
  32918. // 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
  32919. indices.push(pi, pi + shft, pi + 1);
  32920. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32921. pi += 1;
  32922. if (pi === min) {
  32923. p++;
  32924. if (p === lg.length - 1) {
  32925. shft = idx[0] - idx[p];
  32926. l1 = lg[p] - 1;
  32927. l2 = lg[0] - 1;
  32928. }
  32929. else {
  32930. shft = idx[p + 1] - idx[p];
  32931. l1 = lg[p] - 1;
  32932. l2 = lg[p + 1] - 1;
  32933. }
  32934. pi = idx[p];
  32935. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32936. }
  32937. }
  32938. // normals
  32939. VertexData.ComputeNormals(positions, indices, normals);
  32940. if (closePath) {
  32941. var indexFirst = 0;
  32942. var indexLast = 0;
  32943. for (p = 0; p < pathArray.length; p++) {
  32944. indexFirst = idx[p] * 3;
  32945. if (p + 1 < pathArray.length) {
  32946. indexLast = (idx[p + 1] - 1) * 3;
  32947. }
  32948. else {
  32949. indexLast = normals.length - 3;
  32950. }
  32951. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32952. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32953. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32954. normals[indexLast] = normals[indexFirst];
  32955. normals[indexLast + 1] = normals[indexFirst + 1];
  32956. normals[indexLast + 2] = normals[indexFirst + 2];
  32957. }
  32958. }
  32959. // sides
  32960. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32961. // Colors
  32962. var colors = null;
  32963. if (customColors) {
  32964. colors = new Float32Array(customColors.length * 4);
  32965. for (var c = 0; c < customColors.length; c++) {
  32966. colors[c * 4] = customColors[c].r;
  32967. colors[c * 4 + 1] = customColors[c].g;
  32968. colors[c * 4 + 2] = customColors[c].b;
  32969. colors[c * 4 + 3] = customColors[c].a;
  32970. }
  32971. }
  32972. // Result
  32973. var vertexData = new VertexData();
  32974. var positions32 = new Float32Array(positions);
  32975. var normals32 = new Float32Array(normals);
  32976. var uvs32 = new Float32Array(uvs);
  32977. vertexData.indices = indices;
  32978. vertexData.positions = positions32;
  32979. vertexData.normals = normals32;
  32980. vertexData.uvs = uvs32;
  32981. if (colors) {
  32982. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32983. }
  32984. if (closePath) {
  32985. vertexData._idx = idx;
  32986. }
  32987. return vertexData;
  32988. };
  32989. /**
  32990. * Creates the VertexData of the Box.
  32991. */
  32992. VertexData.CreateBox = function (options) {
  32993. var normalsSource = [
  32994. new BABYLON.Vector3(0, 0, 1),
  32995. new BABYLON.Vector3(0, 0, -1),
  32996. new BABYLON.Vector3(1, 0, 0),
  32997. new BABYLON.Vector3(-1, 0, 0),
  32998. new BABYLON.Vector3(0, 1, 0),
  32999. new BABYLON.Vector3(0, -1, 0)
  33000. ];
  33001. var indices = [];
  33002. var positions = [];
  33003. var normals = [];
  33004. var uvs = [];
  33005. var width = options.width || options.size || 1;
  33006. var height = options.height || options.size || 1;
  33007. var depth = options.depth || options.size || 1;
  33008. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33009. var faceUV = options.faceUV || new Array(6);
  33010. var faceColors = options.faceColors;
  33011. var colors = [];
  33012. // default face colors and UV if undefined
  33013. for (var f = 0; f < 6; f++) {
  33014. if (faceUV[f] === undefined) {
  33015. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33016. }
  33017. if (faceColors && faceColors[f] === undefined) {
  33018. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33019. }
  33020. }
  33021. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33022. // Create each face in turn.
  33023. for (var index = 0; index < normalsSource.length; index++) {
  33024. var normal = normalsSource[index];
  33025. // Get two vectors perpendicular to the face normal and to each other.
  33026. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33027. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33028. // Six indices (two triangles) per face.
  33029. var verticesLength = positions.length / 3;
  33030. indices.push(verticesLength);
  33031. indices.push(verticesLength + 1);
  33032. indices.push(verticesLength + 2);
  33033. indices.push(verticesLength);
  33034. indices.push(verticesLength + 2);
  33035. indices.push(verticesLength + 3);
  33036. // Four vertices per face.
  33037. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33038. positions.push(vertex.x, vertex.y, vertex.z);
  33039. normals.push(normal.x, normal.y, normal.z);
  33040. uvs.push(faceUV[index].z, faceUV[index].w);
  33041. if (faceColors) {
  33042. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33043. }
  33044. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33045. positions.push(vertex.x, vertex.y, vertex.z);
  33046. normals.push(normal.x, normal.y, normal.z);
  33047. uvs.push(faceUV[index].x, faceUV[index].w);
  33048. if (faceColors) {
  33049. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33050. }
  33051. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33052. positions.push(vertex.x, vertex.y, vertex.z);
  33053. normals.push(normal.x, normal.y, normal.z);
  33054. uvs.push(faceUV[index].x, faceUV[index].y);
  33055. if (faceColors) {
  33056. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33057. }
  33058. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33059. positions.push(vertex.x, vertex.y, vertex.z);
  33060. normals.push(normal.x, normal.y, normal.z);
  33061. uvs.push(faceUV[index].z, faceUV[index].y);
  33062. if (faceColors) {
  33063. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33064. }
  33065. }
  33066. // sides
  33067. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33068. // Result
  33069. var vertexData = new VertexData();
  33070. vertexData.indices = indices;
  33071. vertexData.positions = positions;
  33072. vertexData.normals = normals;
  33073. vertexData.uvs = uvs;
  33074. if (faceColors) {
  33075. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33076. vertexData.colors = totalColors;
  33077. }
  33078. return vertexData;
  33079. };
  33080. /**
  33081. * Creates the VertexData of the Sphere.
  33082. */
  33083. VertexData.CreateSphere = function (options) {
  33084. var segments = options.segments || 32;
  33085. var diameterX = options.diameterX || options.diameter || 1;
  33086. var diameterY = options.diameterY || options.diameter || 1;
  33087. var diameterZ = options.diameterZ || options.diameter || 1;
  33088. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33089. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33090. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33091. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33092. var totalZRotationSteps = 2 + segments;
  33093. var totalYRotationSteps = 2 * totalZRotationSteps;
  33094. var indices = [];
  33095. var positions = [];
  33096. var normals = [];
  33097. var uvs = [];
  33098. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33099. var normalizedZ = zRotationStep / totalZRotationSteps;
  33100. var angleZ = normalizedZ * Math.PI * slice;
  33101. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33102. var normalizedY = yRotationStep / totalYRotationSteps;
  33103. var angleY = normalizedY * Math.PI * 2 * arc;
  33104. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33105. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33106. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33107. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33108. var vertex = complete.multiply(radius);
  33109. var normal = complete.divide(radius).normalize();
  33110. positions.push(vertex.x, vertex.y, vertex.z);
  33111. normals.push(normal.x, normal.y, normal.z);
  33112. uvs.push(normalizedY, normalizedZ);
  33113. }
  33114. if (zRotationStep > 0) {
  33115. var verticesCount = positions.length / 3;
  33116. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33117. indices.push((firstIndex));
  33118. indices.push((firstIndex + 1));
  33119. indices.push(firstIndex + totalYRotationSteps + 1);
  33120. indices.push((firstIndex + totalYRotationSteps + 1));
  33121. indices.push((firstIndex + 1));
  33122. indices.push((firstIndex + totalYRotationSteps + 2));
  33123. }
  33124. }
  33125. }
  33126. // Sides
  33127. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33128. // Result
  33129. var vertexData = new VertexData();
  33130. vertexData.indices = indices;
  33131. vertexData.positions = positions;
  33132. vertexData.normals = normals;
  33133. vertexData.uvs = uvs;
  33134. return vertexData;
  33135. };
  33136. /**
  33137. * Creates the VertexData of the Cylinder or Cone.
  33138. */
  33139. VertexData.CreateCylinder = function (options) {
  33140. var height = options.height || 2;
  33141. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33142. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33143. var tessellation = options.tessellation || 24;
  33144. var subdivisions = options.subdivisions || 1;
  33145. var hasRings = options.hasRings ? true : false;
  33146. var enclose = options.enclose ? true : false;
  33147. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33148. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33149. var faceUV = options.faceUV || new Array(3);
  33150. var faceColors = options.faceColors;
  33151. // default face colors and UV if undefined
  33152. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33153. var ringNb = (hasRings) ? subdivisions : 1;
  33154. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33155. var f;
  33156. for (f = 0; f < surfaceNb; f++) {
  33157. if (faceColors && faceColors[f] === undefined) {
  33158. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33159. }
  33160. }
  33161. for (f = 0; f < surfaceNb; f++) {
  33162. if (faceUV && faceUV[f] === undefined) {
  33163. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33164. }
  33165. }
  33166. var indices = new Array();
  33167. var positions = new Array();
  33168. var normals = new Array();
  33169. var uvs = new Array();
  33170. var colors = new Array();
  33171. var angle_step = Math.PI * 2 * arc / tessellation;
  33172. var angle;
  33173. var h;
  33174. var radius;
  33175. var tan = (diameterBottom - diameterTop) / 2 / height;
  33176. var ringVertex = BABYLON.Vector3.Zero();
  33177. var ringNormal = BABYLON.Vector3.Zero();
  33178. var ringFirstVertex = BABYLON.Vector3.Zero();
  33179. var ringFirstNormal = BABYLON.Vector3.Zero();
  33180. var quadNormal = BABYLON.Vector3.Zero();
  33181. var Y = BABYLON.Axis.Y;
  33182. // positions, normals, uvs
  33183. var i;
  33184. var j;
  33185. var r;
  33186. var ringIdx = 1;
  33187. var s = 1; // surface index
  33188. var cs = 0;
  33189. var v = 0;
  33190. for (i = 0; i <= subdivisions; i++) {
  33191. h = i / subdivisions;
  33192. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33193. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33194. for (r = 0; r < ringIdx; r++) {
  33195. if (hasRings) {
  33196. s += r;
  33197. }
  33198. if (enclose) {
  33199. s += 2 * r;
  33200. }
  33201. for (j = 0; j <= tessellation; j++) {
  33202. angle = j * angle_step;
  33203. // position
  33204. ringVertex.x = Math.cos(-angle) * radius;
  33205. ringVertex.y = -height / 2 + h * height;
  33206. ringVertex.z = Math.sin(-angle) * radius;
  33207. // normal
  33208. if (diameterTop === 0 && i === subdivisions) {
  33209. // if no top cap, reuse former normals
  33210. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33211. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33212. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33213. }
  33214. else {
  33215. ringNormal.x = ringVertex.x;
  33216. ringNormal.z = ringVertex.z;
  33217. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33218. ringNormal.normalize();
  33219. }
  33220. // keep first ring vertex values for enclose
  33221. if (j === 0) {
  33222. ringFirstVertex.copyFrom(ringVertex);
  33223. ringFirstNormal.copyFrom(ringNormal);
  33224. }
  33225. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33226. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33227. if (hasRings) {
  33228. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33229. }
  33230. else {
  33231. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33232. }
  33233. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33234. if (faceColors) {
  33235. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33236. }
  33237. }
  33238. // if enclose, add four vertices and their dedicated normals
  33239. if (arc !== 1 && enclose) {
  33240. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33241. positions.push(0, ringVertex.y, 0);
  33242. positions.push(0, ringVertex.y, 0);
  33243. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33244. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33245. quadNormal.normalize();
  33246. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33247. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33248. quadNormal.normalize();
  33249. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33250. if (hasRings) {
  33251. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33252. }
  33253. else {
  33254. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33255. }
  33256. uvs.push(faceUV[s + 1].x, v);
  33257. uvs.push(faceUV[s + 1].z, v);
  33258. if (hasRings) {
  33259. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33260. }
  33261. else {
  33262. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33263. }
  33264. uvs.push(faceUV[s + 2].x, v);
  33265. uvs.push(faceUV[s + 2].z, v);
  33266. if (faceColors) {
  33267. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33268. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33269. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33270. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33271. }
  33272. }
  33273. if (cs !== s) {
  33274. cs = s;
  33275. }
  33276. }
  33277. }
  33278. // indices
  33279. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33280. var s;
  33281. i = 0;
  33282. for (s = 0; s < subdivisions; s++) {
  33283. var i0 = 0;
  33284. var i1 = 0;
  33285. var i2 = 0;
  33286. var i3 = 0;
  33287. for (j = 0; j < tessellation; j++) {
  33288. i0 = i * (e + 1) + j;
  33289. i1 = (i + 1) * (e + 1) + j;
  33290. i2 = i * (e + 1) + (j + 1);
  33291. i3 = (i + 1) * (e + 1) + (j + 1);
  33292. indices.push(i0, i1, i2);
  33293. indices.push(i3, i2, i1);
  33294. }
  33295. if (arc !== 1 && enclose) {
  33296. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33297. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33298. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33299. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33300. }
  33301. i = (hasRings) ? (i + 2) : (i + 1);
  33302. }
  33303. // Caps
  33304. var createCylinderCap = function (isTop) {
  33305. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33306. if (radius === 0) {
  33307. return;
  33308. }
  33309. // Cap positions, normals & uvs
  33310. var angle;
  33311. var circleVector;
  33312. var i;
  33313. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33314. var c = null;
  33315. if (faceColors) {
  33316. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33317. }
  33318. // cap center
  33319. var vbase = positions.length / 3;
  33320. var offset = isTop ? height / 2 : -height / 2;
  33321. var center = new BABYLON.Vector3(0, offset, 0);
  33322. positions.push(center.x, center.y, center.z);
  33323. normals.push(0, isTop ? 1 : -1, 0);
  33324. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33325. if (c) {
  33326. colors.push(c.r, c.g, c.b, c.a);
  33327. }
  33328. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33329. for (i = 0; i <= tessellation; i++) {
  33330. angle = Math.PI * 2 * i * arc / tessellation;
  33331. var cos = Math.cos(-angle);
  33332. var sin = Math.sin(-angle);
  33333. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33334. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33335. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33336. normals.push(0, isTop ? 1 : -1, 0);
  33337. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33338. if (c) {
  33339. colors.push(c.r, c.g, c.b, c.a);
  33340. }
  33341. }
  33342. // Cap indices
  33343. for (i = 0; i < tessellation; i++) {
  33344. if (!isTop) {
  33345. indices.push(vbase);
  33346. indices.push(vbase + (i + 1));
  33347. indices.push(vbase + (i + 2));
  33348. }
  33349. else {
  33350. indices.push(vbase);
  33351. indices.push(vbase + (i + 2));
  33352. indices.push(vbase + (i + 1));
  33353. }
  33354. }
  33355. };
  33356. // add caps to geometry
  33357. createCylinderCap(false);
  33358. createCylinderCap(true);
  33359. // Sides
  33360. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33361. var vertexData = new VertexData();
  33362. vertexData.indices = indices;
  33363. vertexData.positions = positions;
  33364. vertexData.normals = normals;
  33365. vertexData.uvs = uvs;
  33366. if (faceColors) {
  33367. vertexData.colors = colors;
  33368. }
  33369. return vertexData;
  33370. };
  33371. /**
  33372. * Creates the VertexData of the Torus.
  33373. */
  33374. VertexData.CreateTorus = function (options) {
  33375. var indices = [];
  33376. var positions = [];
  33377. var normals = [];
  33378. var uvs = [];
  33379. var diameter = options.diameter || 1;
  33380. var thickness = options.thickness || 0.5;
  33381. var tessellation = options.tessellation || 16;
  33382. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33383. var stride = tessellation + 1;
  33384. for (var i = 0; i <= tessellation; i++) {
  33385. var u = i / tessellation;
  33386. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33387. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33388. for (var j = 0; j <= tessellation; j++) {
  33389. var v = 1 - j / tessellation;
  33390. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33391. var dx = Math.cos(innerAngle);
  33392. var dy = Math.sin(innerAngle);
  33393. // Create a vertex.
  33394. var normal = new BABYLON.Vector3(dx, dy, 0);
  33395. var position = normal.scale(thickness / 2);
  33396. var textureCoordinate = new BABYLON.Vector2(u, v);
  33397. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33398. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33399. positions.push(position.x, position.y, position.z);
  33400. normals.push(normal.x, normal.y, normal.z);
  33401. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33402. // And create indices for two triangles.
  33403. var nextI = (i + 1) % stride;
  33404. var nextJ = (j + 1) % stride;
  33405. indices.push(i * stride + j);
  33406. indices.push(i * stride + nextJ);
  33407. indices.push(nextI * stride + j);
  33408. indices.push(i * stride + nextJ);
  33409. indices.push(nextI * stride + nextJ);
  33410. indices.push(nextI * stride + j);
  33411. }
  33412. }
  33413. // Sides
  33414. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33415. // Result
  33416. var vertexData = new VertexData();
  33417. vertexData.indices = indices;
  33418. vertexData.positions = positions;
  33419. vertexData.normals = normals;
  33420. vertexData.uvs = uvs;
  33421. return vertexData;
  33422. };
  33423. /**
  33424. * Creates the VertexData of the LineSystem.
  33425. */
  33426. VertexData.CreateLineSystem = function (options) {
  33427. var indices = [];
  33428. var positions = [];
  33429. var lines = options.lines;
  33430. var colors = options.colors;
  33431. var vertexColors = [];
  33432. var idx = 0;
  33433. for (var l = 0; l < lines.length; l++) {
  33434. var points = lines[l];
  33435. for (var index = 0; index < points.length; index++) {
  33436. positions.push(points[index].x, points[index].y, points[index].z);
  33437. if (colors) {
  33438. var color = colors[l];
  33439. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33440. }
  33441. if (index > 0) {
  33442. indices.push(idx - 1);
  33443. indices.push(idx);
  33444. }
  33445. idx++;
  33446. }
  33447. }
  33448. var vertexData = new VertexData();
  33449. vertexData.indices = indices;
  33450. vertexData.positions = positions;
  33451. if (colors) {
  33452. vertexData.colors = vertexColors;
  33453. }
  33454. return vertexData;
  33455. };
  33456. /**
  33457. * Create the VertexData of the DashedLines.
  33458. */
  33459. VertexData.CreateDashedLines = function (options) {
  33460. var dashSize = options.dashSize || 3;
  33461. var gapSize = options.gapSize || 1;
  33462. var dashNb = options.dashNb || 200;
  33463. var points = options.points;
  33464. var positions = new Array();
  33465. var indices = new Array();
  33466. var curvect = BABYLON.Vector3.Zero();
  33467. var lg = 0;
  33468. var nb = 0;
  33469. var shft = 0;
  33470. var dashshft = 0;
  33471. var curshft = 0;
  33472. var idx = 0;
  33473. var i = 0;
  33474. for (i = 0; i < points.length - 1; i++) {
  33475. points[i + 1].subtractToRef(points[i], curvect);
  33476. lg += curvect.length();
  33477. }
  33478. shft = lg / dashNb;
  33479. dashshft = dashSize * shft / (dashSize + gapSize);
  33480. for (i = 0; i < points.length - 1; i++) {
  33481. points[i + 1].subtractToRef(points[i], curvect);
  33482. nb = Math.floor(curvect.length() / shft);
  33483. curvect.normalize();
  33484. for (var j = 0; j < nb; j++) {
  33485. curshft = shft * j;
  33486. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33487. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33488. indices.push(idx, idx + 1);
  33489. idx += 2;
  33490. }
  33491. }
  33492. // Result
  33493. var vertexData = new VertexData();
  33494. vertexData.positions = positions;
  33495. vertexData.indices = indices;
  33496. return vertexData;
  33497. };
  33498. /**
  33499. * Creates the VertexData of the Ground.
  33500. */
  33501. VertexData.CreateGround = function (options) {
  33502. var indices = [];
  33503. var positions = [];
  33504. var normals = [];
  33505. var uvs = [];
  33506. var row, col;
  33507. var width = options.width || 1;
  33508. var height = options.height || 1;
  33509. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33510. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33511. for (row = 0; row <= subdivisionsY; row++) {
  33512. for (col = 0; col <= subdivisionsX; col++) {
  33513. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33514. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33515. positions.push(position.x, position.y, position.z);
  33516. normals.push(normal.x, normal.y, normal.z);
  33517. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33518. }
  33519. }
  33520. for (row = 0; row < subdivisionsY; row++) {
  33521. for (col = 0; col < subdivisionsX; col++) {
  33522. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33523. indices.push(col + 1 + row * (subdivisionsX + 1));
  33524. indices.push(col + row * (subdivisionsX + 1));
  33525. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33526. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33527. indices.push(col + row * (subdivisionsX + 1));
  33528. }
  33529. }
  33530. // Result
  33531. var vertexData = new VertexData();
  33532. vertexData.indices = indices;
  33533. vertexData.positions = positions;
  33534. vertexData.normals = normals;
  33535. vertexData.uvs = uvs;
  33536. return vertexData;
  33537. };
  33538. /**
  33539. * Creates the VertexData of the TiledGround.
  33540. */
  33541. VertexData.CreateTiledGround = function (options) {
  33542. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33543. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33544. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33545. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33546. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33547. var precision = options.precision || { w: 1, h: 1 };
  33548. var indices = new Array();
  33549. var positions = new Array();
  33550. var normals = new Array();
  33551. var uvs = new Array();
  33552. var row, col, tileRow, tileCol;
  33553. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33554. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33555. precision.w = (precision.w < 1) ? 1 : precision.w;
  33556. precision.h = (precision.h < 1) ? 1 : precision.h;
  33557. var tileSize = {
  33558. 'w': (xmax - xmin) / subdivisions.w,
  33559. 'h': (zmax - zmin) / subdivisions.h
  33560. };
  33561. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33562. // Indices
  33563. var base = positions.length / 3;
  33564. var rowLength = precision.w + 1;
  33565. for (row = 0; row < precision.h; row++) {
  33566. for (col = 0; col < precision.w; col++) {
  33567. var square = [
  33568. base + col + row * rowLength,
  33569. base + (col + 1) + row * rowLength,
  33570. base + (col + 1) + (row + 1) * rowLength,
  33571. base + col + (row + 1) * rowLength
  33572. ];
  33573. indices.push(square[1]);
  33574. indices.push(square[2]);
  33575. indices.push(square[3]);
  33576. indices.push(square[0]);
  33577. indices.push(square[1]);
  33578. indices.push(square[3]);
  33579. }
  33580. }
  33581. // Position, normals and uvs
  33582. var position = BABYLON.Vector3.Zero();
  33583. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33584. for (row = 0; row <= precision.h; row++) {
  33585. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33586. for (col = 0; col <= precision.w; col++) {
  33587. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33588. position.y = 0;
  33589. positions.push(position.x, position.y, position.z);
  33590. normals.push(normal.x, normal.y, normal.z);
  33591. uvs.push(col / precision.w, row / precision.h);
  33592. }
  33593. }
  33594. }
  33595. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33596. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33597. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33598. }
  33599. }
  33600. // Result
  33601. var vertexData = new VertexData();
  33602. vertexData.indices = indices;
  33603. vertexData.positions = positions;
  33604. vertexData.normals = normals;
  33605. vertexData.uvs = uvs;
  33606. return vertexData;
  33607. };
  33608. /**
  33609. * Creates the VertexData of the Ground designed from a heightmap.
  33610. */
  33611. VertexData.CreateGroundFromHeightMap = function (options) {
  33612. var indices = [];
  33613. var positions = [];
  33614. var normals = [];
  33615. var uvs = [];
  33616. var row, col;
  33617. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33618. // Vertices
  33619. for (row = 0; row <= options.subdivisions; row++) {
  33620. for (col = 0; col <= options.subdivisions; col++) {
  33621. 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));
  33622. // Compute height
  33623. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33624. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33625. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33626. var r = options.buffer[pos] / 255.0;
  33627. var g = options.buffer[pos + 1] / 255.0;
  33628. var b = options.buffer[pos + 2] / 255.0;
  33629. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33630. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33631. // Add vertex
  33632. positions.push(position.x, position.y, position.z);
  33633. normals.push(0, 0, 0);
  33634. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33635. }
  33636. }
  33637. // Indices
  33638. for (row = 0; row < options.subdivisions; row++) {
  33639. for (col = 0; col < options.subdivisions; col++) {
  33640. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33641. indices.push(col + 1 + row * (options.subdivisions + 1));
  33642. indices.push(col + row * (options.subdivisions + 1));
  33643. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33644. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33645. indices.push(col + row * (options.subdivisions + 1));
  33646. }
  33647. }
  33648. // Normals
  33649. VertexData.ComputeNormals(positions, indices, normals);
  33650. // Result
  33651. var vertexData = new VertexData();
  33652. vertexData.indices = indices;
  33653. vertexData.positions = positions;
  33654. vertexData.normals = normals;
  33655. vertexData.uvs = uvs;
  33656. return vertexData;
  33657. };
  33658. /**
  33659. * Creates the VertexData of the Plane.
  33660. */
  33661. VertexData.CreatePlane = function (options) {
  33662. var indices = [];
  33663. var positions = [];
  33664. var normals = [];
  33665. var uvs = [];
  33666. var width = options.width || options.size || 1;
  33667. var height = options.height || options.size || 1;
  33668. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33669. // Vertices
  33670. var halfWidth = width / 2.0;
  33671. var halfHeight = height / 2.0;
  33672. positions.push(-halfWidth, -halfHeight, 0);
  33673. normals.push(0, 0, -1.0);
  33674. uvs.push(0.0, 0.0);
  33675. positions.push(halfWidth, -halfHeight, 0);
  33676. normals.push(0, 0, -1.0);
  33677. uvs.push(1.0, 0.0);
  33678. positions.push(halfWidth, halfHeight, 0);
  33679. normals.push(0, 0, -1.0);
  33680. uvs.push(1.0, 1.0);
  33681. positions.push(-halfWidth, halfHeight, 0);
  33682. normals.push(0, 0, -1.0);
  33683. uvs.push(0.0, 1.0);
  33684. // Indices
  33685. indices.push(0);
  33686. indices.push(1);
  33687. indices.push(2);
  33688. indices.push(0);
  33689. indices.push(2);
  33690. indices.push(3);
  33691. // Sides
  33692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  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 Disc or regular Polygon.
  33703. */
  33704. VertexData.CreateDisc = function (options) {
  33705. var positions = new Array();
  33706. var indices = new Array();
  33707. var normals = new Array();
  33708. var uvs = new Array();
  33709. var radius = options.radius || 0.5;
  33710. var tessellation = options.tessellation || 64;
  33711. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33712. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33713. // positions and uvs
  33714. positions.push(0, 0, 0); // disc center first
  33715. uvs.push(0.5, 0.5);
  33716. var theta = Math.PI * 2 * arc;
  33717. var step = theta / tessellation;
  33718. for (var a = 0; a < theta; a += step) {
  33719. var x = Math.cos(a);
  33720. var y = Math.sin(a);
  33721. var u = (x + 1) / 2;
  33722. var v = (1 - y) / 2;
  33723. positions.push(radius * x, radius * y, 0);
  33724. uvs.push(u, v);
  33725. }
  33726. if (arc === 1) {
  33727. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33728. uvs.push(uvs[2], uvs[3]);
  33729. }
  33730. //indices
  33731. var vertexNb = positions.length / 3;
  33732. for (var i = 1; i < vertexNb - 1; i++) {
  33733. indices.push(i + 1, 0, i);
  33734. }
  33735. // result
  33736. VertexData.ComputeNormals(positions, indices, normals);
  33737. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33738. var vertexData = new VertexData();
  33739. vertexData.indices = indices;
  33740. vertexData.positions = positions;
  33741. vertexData.normals = normals;
  33742. vertexData.uvs = uvs;
  33743. return vertexData;
  33744. };
  33745. /**
  33746. * Re-creates the VertexData of the Polygon for sideOrientation.
  33747. */
  33748. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33749. var faceUV = fUV || new Array(3);
  33750. var faceColors = fColors;
  33751. var colors = [];
  33752. // default face colors and UV if undefined
  33753. for (var f = 0; f < 3; f++) {
  33754. if (faceUV[f] === undefined) {
  33755. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33756. }
  33757. if (faceColors && faceColors[f] === undefined) {
  33758. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33759. }
  33760. }
  33761. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33762. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33763. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33764. var indices = polygon.getIndices();
  33765. // set face colours and textures
  33766. var idx = 0;
  33767. var face = 0;
  33768. for (var index = 0; index < normals.length; index += 3) {
  33769. //Edge Face no. 1
  33770. if (Math.abs(normals[index + 1]) < 0.001) {
  33771. face = 1;
  33772. }
  33773. //Top Face no. 0
  33774. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33775. face = 0;
  33776. }
  33777. //Bottom Face no. 2
  33778. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33779. face = 2;
  33780. }
  33781. idx = index / 3;
  33782. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33783. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33784. if (faceColors) {
  33785. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33786. }
  33787. }
  33788. // sides
  33789. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33790. // Result
  33791. var vertexData = new VertexData();
  33792. vertexData.indices = indices;
  33793. vertexData.positions = positions;
  33794. vertexData.normals = normals;
  33795. vertexData.uvs = uvs;
  33796. if (faceColors) {
  33797. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33798. vertexData.colors = totalColors;
  33799. }
  33800. return vertexData;
  33801. };
  33802. /**
  33803. * Creates the VertexData of the IcoSphere.
  33804. */
  33805. VertexData.CreateIcoSphere = function (options) {
  33806. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33807. var radius = options.radius || 1;
  33808. var flat = (options.flat === undefined) ? true : options.flat;
  33809. var subdivisions = options.subdivisions || 4;
  33810. var radiusX = options.radiusX || radius;
  33811. var radiusY = options.radiusY || radius;
  33812. var radiusZ = options.radiusZ || radius;
  33813. var t = (1 + Math.sqrt(5)) / 2;
  33814. // 12 vertex x,y,z
  33815. var ico_vertices = [
  33816. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33817. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33818. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33819. ];
  33820. // index of 3 vertex makes a face of icopshere
  33821. var ico_indices = [
  33822. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33823. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33824. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33825. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33826. ];
  33827. // vertex for uv have aliased position, not for UV
  33828. var vertices_unalias_id = [
  33829. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33830. // vertex alias
  33831. 0,
  33832. 2,
  33833. 3,
  33834. 3,
  33835. 3,
  33836. 4,
  33837. 7,
  33838. 8,
  33839. 9,
  33840. 9,
  33841. 10,
  33842. 11 // 23: B + 12
  33843. ];
  33844. // uv as integer step (not pixels !)
  33845. var ico_vertexuv = [
  33846. 5, 1, 3, 1, 6, 4, 0, 0,
  33847. 5, 3, 4, 2, 2, 2, 4, 0,
  33848. 2, 0, 1, 1, 6, 0, 6, 2,
  33849. // vertex alias (for same vertex on different faces)
  33850. 0, 4,
  33851. 3, 3,
  33852. 4, 4,
  33853. 3, 1,
  33854. 4, 2,
  33855. 4, 4,
  33856. 0, 2,
  33857. 1, 1,
  33858. 2, 2,
  33859. 3, 3,
  33860. 1, 3,
  33861. 2, 4 // 23: B + 12
  33862. ];
  33863. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33864. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33865. // First island of uv mapping
  33866. // v = 4h 3+ 2
  33867. // v = 3h 9+ 4
  33868. // v = 2h 9+ 5 B
  33869. // v = 1h 9 1 0
  33870. // v = 0h 3 8 7 A
  33871. // u = 0 1 2 3 4 5 6 *a
  33872. // Second island of uv mapping
  33873. // v = 4h 0+ B+ 4+
  33874. // v = 3h A+ 2+
  33875. // v = 2h 7+ 6 3+
  33876. // v = 1h 8+ 3+
  33877. // v = 0h
  33878. // u = 0 1 2 3 4 5 6 *a
  33879. // Face layout on texture UV mapping
  33880. // ============
  33881. // \ 4 /\ 16 / ======
  33882. // \ / \ / /\ 11 /
  33883. // \/ 7 \/ / \ /
  33884. // ======= / 10 \/
  33885. // /\ 17 /\ =======
  33886. // / \ / \ \ 15 /\
  33887. // / 8 \/ 12 \ \ / \
  33888. // ============ \/ 6 \
  33889. // \ 18 /\ ============
  33890. // \ / \ \ 5 /\ 0 /
  33891. // \/ 13 \ \ / \ /
  33892. // ======= \/ 1 \/
  33893. // =============
  33894. // /\ 19 /\ 2 /\
  33895. // / \ / \ / \
  33896. // / 14 \/ 9 \/ 3 \
  33897. // ===================
  33898. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33899. var ustep = 138 / 1024;
  33900. var vstep = 239 / 1024;
  33901. var uoffset = 60 / 1024;
  33902. var voffset = 26 / 1024;
  33903. // Second island should have margin, not to touch the first island
  33904. // avoid any borderline artefact in pixel rounding
  33905. var island_u_offset = -40 / 1024;
  33906. var island_v_offset = +20 / 1024;
  33907. // face is either island 0 or 1 :
  33908. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33909. var island = [
  33910. 0, 0, 0, 0, 1,
  33911. 0, 0, 1, 1, 0,
  33912. 0, 0, 1, 1, 0,
  33913. 0, 1, 1, 1, 0 // 15 - 19
  33914. ];
  33915. var indices = new Array();
  33916. var positions = new Array();
  33917. var normals = new Array();
  33918. var uvs = new Array();
  33919. var current_indice = 0;
  33920. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33921. var face_vertex_pos = new Array(3);
  33922. var face_vertex_uv = new Array(3);
  33923. var v012;
  33924. for (v012 = 0; v012 < 3; v012++) {
  33925. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33926. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33927. }
  33928. // create all with normals
  33929. for (var face = 0; face < 20; face++) {
  33930. // 3 vertex per face
  33931. for (v012 = 0; v012 < 3; v012++) {
  33932. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33933. var v_id = ico_indices[3 * face + v012];
  33934. // vertex have 3D position (x,y,z)
  33935. 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]);
  33936. // Normalize to get normal, then scale to radius
  33937. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33938. // uv Coordinates from vertex ID
  33939. 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);
  33940. }
  33941. // Subdivide the face (interpolate pos, norm, uv)
  33942. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33943. // - norm is linear interpolation of vertex corner normal
  33944. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33945. // - uv is linear interpolation
  33946. //
  33947. // Topology is as below for sub-divide by 2
  33948. // vertex shown as v0,v1,v2
  33949. // interp index is i1 to progress in range [v0,v1[
  33950. // interp index is i2 to progress in range [v0,v2[
  33951. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33952. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33953. //
  33954. //
  33955. // i2 v2
  33956. // ^ ^
  33957. // / / \
  33958. // / / \
  33959. // / / \
  33960. // / / (0,1) \
  33961. // / #---------\
  33962. // / / \ (0,0)'/ \
  33963. // / / \ / \
  33964. // / / \ / \
  33965. // / / (0,0) \ / (1,0) \
  33966. // / #---------#---------\
  33967. // v0 v1
  33968. //
  33969. // --------------------> i1
  33970. //
  33971. // interp of (i1,i2):
  33972. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33973. // along i1 : lerp(x0,x1, i1/(S-i2))
  33974. //
  33975. // centroid of triangle is needed to get help normal computation
  33976. // (c1,c2) are used for centroid location
  33977. var interp_vertex = function (i1, i2, c1, c2) {
  33978. // vertex is interpolated from
  33979. // - face_vertex_pos[0..2]
  33980. // - face_vertex_uv[0..2]
  33981. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33982. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33983. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33984. pos_interp.normalize();
  33985. var vertex_normal;
  33986. if (flat) {
  33987. // in flat mode, recalculate normal as face centroid normal
  33988. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33989. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33990. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33991. }
  33992. else {
  33993. // in smooth mode, recalculate normal from each single vertex position
  33994. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33995. }
  33996. // Vertex normal need correction due to X,Y,Z radius scaling
  33997. vertex_normal.x /= radiusX;
  33998. vertex_normal.y /= radiusY;
  33999. vertex_normal.z /= radiusZ;
  34000. vertex_normal.normalize();
  34001. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34002. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34003. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34004. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34005. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34006. uvs.push(uv_interp.x, uv_interp.y);
  34007. // push each vertex has member of a face
  34008. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34009. indices.push(current_indice);
  34010. current_indice++;
  34011. };
  34012. for (var i2 = 0; i2 < subdivisions; i2++) {
  34013. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34014. // face : (i1,i2) for /\ :
  34015. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34016. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34017. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34018. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34019. if (i1 + i2 + 1 < subdivisions) {
  34020. // face : (i1,i2)' for \/ :
  34021. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34022. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34023. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34024. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34025. }
  34026. }
  34027. }
  34028. }
  34029. // Sides
  34030. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34031. // Result
  34032. var vertexData = new VertexData();
  34033. vertexData.indices = indices;
  34034. vertexData.positions = positions;
  34035. vertexData.normals = normals;
  34036. vertexData.uvs = uvs;
  34037. return vertexData;
  34038. };
  34039. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34040. /**
  34041. * Creates the VertexData of the Polyhedron.
  34042. */
  34043. VertexData.CreatePolyhedron = function (options) {
  34044. // provided polyhedron types :
  34045. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34046. // 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)
  34047. var polyhedra = [];
  34048. 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]] };
  34049. 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]] };
  34050. polyhedra[2] = {
  34051. 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]],
  34052. 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]]
  34053. };
  34054. polyhedra[3] = {
  34055. 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]],
  34056. 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]]
  34057. };
  34058. polyhedra[4] = {
  34059. 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]],
  34060. 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]]
  34061. };
  34062. 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]] };
  34063. 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]] };
  34064. 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]] };
  34065. 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]] };
  34066. 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]] };
  34067. 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]] };
  34068. 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]] };
  34069. 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]] };
  34070. 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]] };
  34071. polyhedra[14] = {
  34072. 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]],
  34073. 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]]
  34074. };
  34075. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34076. var size = options.size;
  34077. var sizeX = options.sizeX || size || 1;
  34078. var sizeY = options.sizeY || size || 1;
  34079. var sizeZ = options.sizeZ || size || 1;
  34080. var data = options.custom || polyhedra[type];
  34081. var nbfaces = data.face.length;
  34082. var faceUV = options.faceUV || new Array(nbfaces);
  34083. var faceColors = options.faceColors;
  34084. var flat = (options.flat === undefined) ? true : options.flat;
  34085. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34086. var positions = new Array();
  34087. var indices = new Array();
  34088. var normals = new Array();
  34089. var uvs = new Array();
  34090. var colors = new Array();
  34091. var index = 0;
  34092. var faceIdx = 0; // face cursor in the array "indexes"
  34093. var indexes = new Array();
  34094. var i = 0;
  34095. var f = 0;
  34096. var u, v, ang, x, y, tmp;
  34097. // default face colors and UV if undefined
  34098. if (flat) {
  34099. for (f = 0; f < nbfaces; f++) {
  34100. if (faceColors && faceColors[f] === undefined) {
  34101. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34102. }
  34103. if (faceUV && faceUV[f] === undefined) {
  34104. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34105. }
  34106. }
  34107. }
  34108. if (!flat) {
  34109. for (i = 0; i < data.vertex.length; i++) {
  34110. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34111. uvs.push(0, 0);
  34112. }
  34113. for (f = 0; f < nbfaces; f++) {
  34114. for (i = 0; i < data.face[f].length - 2; i++) {
  34115. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34116. }
  34117. }
  34118. }
  34119. else {
  34120. for (f = 0; f < nbfaces; f++) {
  34121. var fl = data.face[f].length; // number of vertices of the current face
  34122. ang = 2 * Math.PI / fl;
  34123. x = 0.5 * Math.tan(ang / 2);
  34124. y = 0.5;
  34125. // positions, uvs, colors
  34126. for (i = 0; i < fl; i++) {
  34127. // positions
  34128. 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);
  34129. indexes.push(index);
  34130. index++;
  34131. // uvs
  34132. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34133. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34134. uvs.push(u, v);
  34135. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34136. y = x * Math.sin(ang) + y * Math.cos(ang);
  34137. x = tmp;
  34138. // colors
  34139. if (faceColors) {
  34140. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34141. }
  34142. }
  34143. // indices from indexes
  34144. for (i = 0; i < fl - 2; i++) {
  34145. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34146. }
  34147. faceIdx += fl;
  34148. }
  34149. }
  34150. VertexData.ComputeNormals(positions, indices, normals);
  34151. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34152. var vertexData = new VertexData();
  34153. vertexData.positions = positions;
  34154. vertexData.indices = indices;
  34155. vertexData.normals = normals;
  34156. vertexData.uvs = uvs;
  34157. if (faceColors && flat) {
  34158. vertexData.colors = colors;
  34159. }
  34160. return vertexData;
  34161. };
  34162. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34163. /**
  34164. * Creates the VertexData of the Torus Knot.
  34165. */
  34166. VertexData.CreateTorusKnot = function (options) {
  34167. var indices = new Array();
  34168. var positions = new Array();
  34169. var normals = new Array();
  34170. var uvs = new Array();
  34171. var radius = options.radius || 2;
  34172. var tube = options.tube || 0.5;
  34173. var radialSegments = options.radialSegments || 32;
  34174. var tubularSegments = options.tubularSegments || 32;
  34175. var p = options.p || 2;
  34176. var q = options.q || 3;
  34177. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34178. // Helper
  34179. var getPos = function (angle) {
  34180. var cu = Math.cos(angle);
  34181. var su = Math.sin(angle);
  34182. var quOverP = q / p * angle;
  34183. var cs = Math.cos(quOverP);
  34184. var tx = radius * (2 + cs) * 0.5 * cu;
  34185. var ty = radius * (2 + cs) * su * 0.5;
  34186. var tz = radius * Math.sin(quOverP) * 0.5;
  34187. return new BABYLON.Vector3(tx, ty, tz);
  34188. };
  34189. // Vertices
  34190. var i;
  34191. var j;
  34192. for (i = 0; i <= radialSegments; i++) {
  34193. var modI = i % radialSegments;
  34194. var u = modI / radialSegments * 2 * p * Math.PI;
  34195. var p1 = getPos(u);
  34196. var p2 = getPos(u + 0.01);
  34197. var tang = p2.subtract(p1);
  34198. var n = p2.add(p1);
  34199. var bitan = BABYLON.Vector3.Cross(tang, n);
  34200. n = BABYLON.Vector3.Cross(bitan, tang);
  34201. bitan.normalize();
  34202. n.normalize();
  34203. for (j = 0; j < tubularSegments; j++) {
  34204. var modJ = j % tubularSegments;
  34205. var v = modJ / tubularSegments * 2 * Math.PI;
  34206. var cx = -tube * Math.cos(v);
  34207. var cy = tube * Math.sin(v);
  34208. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34209. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34210. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34211. uvs.push(i / radialSegments);
  34212. uvs.push(j / tubularSegments);
  34213. }
  34214. }
  34215. for (i = 0; i < radialSegments; i++) {
  34216. for (j = 0; j < tubularSegments; j++) {
  34217. var jNext = (j + 1) % tubularSegments;
  34218. var a = i * tubularSegments + j;
  34219. var b = (i + 1) * tubularSegments + j;
  34220. var c = (i + 1) * tubularSegments + jNext;
  34221. var d = i * tubularSegments + jNext;
  34222. indices.push(d);
  34223. indices.push(b);
  34224. indices.push(a);
  34225. indices.push(d);
  34226. indices.push(c);
  34227. indices.push(b);
  34228. }
  34229. }
  34230. // Normals
  34231. VertexData.ComputeNormals(positions, indices, normals);
  34232. // Sides
  34233. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34234. // Result
  34235. var vertexData = new VertexData();
  34236. vertexData.indices = indices;
  34237. vertexData.positions = positions;
  34238. vertexData.normals = normals;
  34239. vertexData.uvs = uvs;
  34240. return vertexData;
  34241. };
  34242. // Tools
  34243. /**
  34244. * @param {any} - positions (number[] or Float32Array)
  34245. * @param {any} - indices (number[] or Uint16Array)
  34246. * @param {any} - normals (number[] or Float32Array)
  34247. * options (optional) :
  34248. * facetPositions : optional array of facet positions (vector3)
  34249. * facetNormals : optional array of facet normals (vector3)
  34250. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34251. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34252. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34253. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34254. * bInfo : optional bounding info, required for facetPartitioning computation
  34255. * useRightHandedSystem: optional boolean to for right handed system computation
  34256. * depthSort : optional boolean to enable the facet depth sort computation
  34257. * distanceTo : optional Vector3 to compute the facet depth from this location
  34258. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34259. */
  34260. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34261. // temporary scalar variables
  34262. var index = 0; // facet index
  34263. var p1p2x = 0.0; // p1p2 vector x coordinate
  34264. var p1p2y = 0.0; // p1p2 vector y coordinate
  34265. var p1p2z = 0.0; // p1p2 vector z coordinate
  34266. var p3p2x = 0.0; // p3p2 vector x coordinate
  34267. var p3p2y = 0.0; // p3p2 vector y coordinate
  34268. var p3p2z = 0.0; // p3p2 vector z coordinate
  34269. var faceNormalx = 0.0; // facet normal x coordinate
  34270. var faceNormaly = 0.0; // facet normal y coordinate
  34271. var faceNormalz = 0.0; // facet normal z coordinate
  34272. var length = 0.0; // facet normal length before normalization
  34273. var v1x = 0; // vector1 x index in the positions array
  34274. var v1y = 0; // vector1 y index in the positions array
  34275. var v1z = 0; // vector1 z index in the positions array
  34276. var v2x = 0; // vector2 x index in the positions array
  34277. var v2y = 0; // vector2 y index in the positions array
  34278. var v2z = 0; // vector2 z index in the positions array
  34279. var v3x = 0; // vector3 x index in the positions array
  34280. var v3y = 0; // vector3 y index in the positions array
  34281. var v3z = 0; // vector3 z index in the positions array
  34282. var computeFacetNormals = false;
  34283. var computeFacetPositions = false;
  34284. var computeFacetPartitioning = false;
  34285. var computeDepthSort = false;
  34286. var faceNormalSign = 1;
  34287. var ratio = 0;
  34288. var distanceTo = null;
  34289. if (options) {
  34290. computeFacetNormals = (options.facetNormals) ? true : false;
  34291. computeFacetPositions = (options.facetPositions) ? true : false;
  34292. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34293. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34294. ratio = options.ratio || 0;
  34295. computeDepthSort = (options.depthSort) ? true : false;
  34296. distanceTo = (options.distanceTo);
  34297. if (computeDepthSort) {
  34298. if (distanceTo === undefined) {
  34299. distanceTo = BABYLON.Vector3.Zero();
  34300. }
  34301. var depthSortedFacets = options.depthSortedFacets;
  34302. }
  34303. }
  34304. // facetPartitioning reinit if needed
  34305. var xSubRatio = 0;
  34306. var ySubRatio = 0;
  34307. var zSubRatio = 0;
  34308. var subSq = 0;
  34309. if (computeFacetPartitioning && options && options.bbSize) {
  34310. var ox = 0; // X partitioning index for facet position
  34311. var oy = 0; // Y partinioning index for facet position
  34312. var oz = 0; // Z partinioning index for facet position
  34313. var b1x = 0; // X partitioning index for facet v1 vertex
  34314. var b1y = 0; // Y partitioning index for facet v1 vertex
  34315. var b1z = 0; // z partitioning index for facet v1 vertex
  34316. var b2x = 0; // X partitioning index for facet v2 vertex
  34317. var b2y = 0; // Y partitioning index for facet v2 vertex
  34318. var b2z = 0; // Z partitioning index for facet v2 vertex
  34319. var b3x = 0; // X partitioning index for facet v3 vertex
  34320. var b3y = 0; // Y partitioning index for facet v3 vertex
  34321. var b3z = 0; // Z partitioning index for facet v3 vertex
  34322. var block_idx_o = 0; // facet barycenter block index
  34323. var block_idx_v1 = 0; // v1 vertex block index
  34324. var block_idx_v2 = 0; // v2 vertex block index
  34325. var block_idx_v3 = 0; // v3 vertex block index
  34326. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34327. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34328. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34329. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34330. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34331. subSq = options.subDiv.max * options.subDiv.max;
  34332. options.facetPartitioning.length = 0;
  34333. }
  34334. // reset the normals
  34335. for (index = 0; index < positions.length; index++) {
  34336. normals[index] = 0.0;
  34337. }
  34338. // Loop : 1 indice triplet = 1 facet
  34339. var nbFaces = (indices.length / 3) | 0;
  34340. for (index = 0; index < nbFaces; index++) {
  34341. // get the indexes of the coordinates of each vertex of the facet
  34342. v1x = indices[index * 3] * 3;
  34343. v1y = v1x + 1;
  34344. v1z = v1x + 2;
  34345. v2x = indices[index * 3 + 1] * 3;
  34346. v2y = v2x + 1;
  34347. v2z = v2x + 2;
  34348. v3x = indices[index * 3 + 2] * 3;
  34349. v3y = v3x + 1;
  34350. v3z = v3x + 2;
  34351. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34352. p1p2y = positions[v1y] - positions[v2y];
  34353. p1p2z = positions[v1z] - positions[v2z];
  34354. p3p2x = positions[v3x] - positions[v2x];
  34355. p3p2y = positions[v3y] - positions[v2y];
  34356. p3p2z = positions[v3z] - positions[v2z];
  34357. // compute the face normal with the cross product
  34358. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34359. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34360. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34361. // normalize this normal and store it in the array facetData
  34362. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34363. length = (length === 0) ? 1.0 : length;
  34364. faceNormalx /= length;
  34365. faceNormaly /= length;
  34366. faceNormalz /= length;
  34367. if (computeFacetNormals && options) {
  34368. options.facetNormals[index].x = faceNormalx;
  34369. options.facetNormals[index].y = faceNormaly;
  34370. options.facetNormals[index].z = faceNormalz;
  34371. }
  34372. if (computeFacetPositions && options) {
  34373. // compute and the facet barycenter coordinates in the array facetPositions
  34374. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34375. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34376. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34377. }
  34378. if (computeFacetPartitioning && options) {
  34379. // store the facet indexes in arrays in the main facetPartitioning array :
  34380. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34381. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34382. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34383. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34384. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34385. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34386. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34387. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34388. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34389. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34390. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34391. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34392. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34393. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34394. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34395. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34396. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34397. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34398. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34399. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34400. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34401. // push each facet index in each block containing the vertex
  34402. options.facetPartitioning[block_idx_v1].push(index);
  34403. if (block_idx_v2 != block_idx_v1) {
  34404. options.facetPartitioning[block_idx_v2].push(index);
  34405. }
  34406. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34407. options.facetPartitioning[block_idx_v3].push(index);
  34408. }
  34409. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34410. options.facetPartitioning[block_idx_o].push(index);
  34411. }
  34412. }
  34413. if (computeDepthSort && options && options.facetPositions) {
  34414. var dsf = depthSortedFacets[index];
  34415. dsf.ind = index * 3;
  34416. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34417. }
  34418. // compute the normals anyway
  34419. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34420. normals[v1y] += faceNormaly;
  34421. normals[v1z] += faceNormalz;
  34422. normals[v2x] += faceNormalx;
  34423. normals[v2y] += faceNormaly;
  34424. normals[v2z] += faceNormalz;
  34425. normals[v3x] += faceNormalx;
  34426. normals[v3y] += faceNormaly;
  34427. normals[v3z] += faceNormalz;
  34428. }
  34429. // last normalization of each normal
  34430. for (index = 0; index < normals.length / 3; index++) {
  34431. faceNormalx = normals[index * 3];
  34432. faceNormaly = normals[index * 3 + 1];
  34433. faceNormalz = normals[index * 3 + 2];
  34434. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34435. length = (length === 0) ? 1.0 : length;
  34436. faceNormalx /= length;
  34437. faceNormaly /= length;
  34438. faceNormalz /= length;
  34439. normals[index * 3] = faceNormalx;
  34440. normals[index * 3 + 1] = faceNormaly;
  34441. normals[index * 3 + 2] = faceNormalz;
  34442. }
  34443. };
  34444. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34445. var li = indices.length;
  34446. var ln = normals.length;
  34447. var i;
  34448. var n;
  34449. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34450. switch (sideOrientation) {
  34451. case BABYLON.Mesh.FRONTSIDE:
  34452. // nothing changed
  34453. break;
  34454. case BABYLON.Mesh.BACKSIDE:
  34455. var tmp;
  34456. // indices
  34457. for (i = 0; i < li; i += 3) {
  34458. tmp = indices[i];
  34459. indices[i] = indices[i + 2];
  34460. indices[i + 2] = tmp;
  34461. }
  34462. // normals
  34463. for (n = 0; n < ln; n++) {
  34464. normals[n] = -normals[n];
  34465. }
  34466. break;
  34467. case BABYLON.Mesh.DOUBLESIDE:
  34468. // positions
  34469. var lp = positions.length;
  34470. var l = lp / 3;
  34471. for (var p = 0; p < lp; p++) {
  34472. positions[lp + p] = positions[p];
  34473. }
  34474. // indices
  34475. for (i = 0; i < li; i += 3) {
  34476. indices[i + li] = indices[i + 2] + l;
  34477. indices[i + 1 + li] = indices[i + 1] + l;
  34478. indices[i + 2 + li] = indices[i] + l;
  34479. }
  34480. // normals
  34481. for (n = 0; n < ln; n++) {
  34482. normals[ln + n] = -normals[n];
  34483. }
  34484. // uvs
  34485. var lu = uvs.length;
  34486. var u = 0;
  34487. for (u = 0; u < lu; u++) {
  34488. uvs[u + lu] = uvs[u];
  34489. }
  34490. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34491. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34492. u = 0;
  34493. for (i = 0; i < lu / 2; i++) {
  34494. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34495. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34496. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34497. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34498. u += 2;
  34499. }
  34500. break;
  34501. }
  34502. };
  34503. /**
  34504. * Creates a new VertexData from the imported parameters.
  34505. */
  34506. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34507. var vertexData = new VertexData();
  34508. // positions
  34509. var positions = parsedVertexData.positions;
  34510. if (positions) {
  34511. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34512. }
  34513. // normals
  34514. var normals = parsedVertexData.normals;
  34515. if (normals) {
  34516. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34517. }
  34518. // tangents
  34519. var tangents = parsedVertexData.tangents;
  34520. if (tangents) {
  34521. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34522. }
  34523. // uvs
  34524. var uvs = parsedVertexData.uvs;
  34525. if (uvs) {
  34526. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34527. }
  34528. // uv2s
  34529. var uv2s = parsedVertexData.uv2s;
  34530. if (uv2s) {
  34531. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34532. }
  34533. // uv3s
  34534. var uv3s = parsedVertexData.uv3s;
  34535. if (uv3s) {
  34536. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34537. }
  34538. // uv4s
  34539. var uv4s = parsedVertexData.uv4s;
  34540. if (uv4s) {
  34541. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34542. }
  34543. // uv5s
  34544. var uv5s = parsedVertexData.uv5s;
  34545. if (uv5s) {
  34546. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34547. }
  34548. // uv6s
  34549. var uv6s = parsedVertexData.uv6s;
  34550. if (uv6s) {
  34551. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34552. }
  34553. // colors
  34554. var colors = parsedVertexData.colors;
  34555. if (colors) {
  34556. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34557. }
  34558. // matricesIndices
  34559. var matricesIndices = parsedVertexData.matricesIndices;
  34560. if (matricesIndices) {
  34561. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34562. }
  34563. // matricesWeights
  34564. var matricesWeights = parsedVertexData.matricesWeights;
  34565. if (matricesWeights) {
  34566. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34567. }
  34568. // indices
  34569. var indices = parsedVertexData.indices;
  34570. if (indices) {
  34571. vertexData.indices = indices;
  34572. }
  34573. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34574. };
  34575. return VertexData;
  34576. }());
  34577. BABYLON.VertexData = VertexData;
  34578. })(BABYLON || (BABYLON = {}));
  34579. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34580. var BABYLON;
  34581. (function (BABYLON) {
  34582. /**
  34583. * Class used to store geometry data (vertex buffers + index buffer)
  34584. */
  34585. var Geometry = /** @class */ (function () {
  34586. /**
  34587. * Creates a new geometry
  34588. * @param id defines the unique ID
  34589. * @param scene defines the hosting scene
  34590. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34591. * @param updatable defines if geometry must be updatable (false by default)
  34592. * @param mesh defines the mesh that will be associated with the geometry
  34593. */
  34594. function Geometry(id, scene, vertexData, updatable, mesh) {
  34595. if (updatable === void 0) { updatable = false; }
  34596. if (mesh === void 0) { mesh = null; }
  34597. /**
  34598. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34599. */
  34600. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34601. this._totalVertices = 0;
  34602. this._isDisposed = false;
  34603. this._indexBufferIsUpdatable = false;
  34604. this.id = id;
  34605. this._engine = scene.getEngine();
  34606. this._meshes = [];
  34607. this._scene = scene;
  34608. //Init vertex buffer cache
  34609. this._vertexBuffers = {};
  34610. this._indices = [];
  34611. this._updatable = updatable;
  34612. // vertexData
  34613. if (vertexData) {
  34614. this.setAllVerticesData(vertexData, updatable);
  34615. }
  34616. else {
  34617. this._totalVertices = 0;
  34618. this._indices = [];
  34619. }
  34620. if (this._engine.getCaps().vertexArrayObject) {
  34621. this._vertexArrayObjects = {};
  34622. }
  34623. // applyToMesh
  34624. if (mesh) {
  34625. if (mesh.getClassName() === "LinesMesh") {
  34626. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34627. this.updateExtend();
  34628. }
  34629. this.applyToMesh(mesh);
  34630. mesh.computeWorldMatrix(true);
  34631. }
  34632. }
  34633. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34634. /**
  34635. * 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
  34636. */
  34637. get: function () {
  34638. return this._boundingBias;
  34639. },
  34640. /**
  34641. * 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
  34642. */
  34643. set: function (value) {
  34644. if (this._boundingBias && this._boundingBias.equals(value)) {
  34645. return;
  34646. }
  34647. this._boundingBias = value.clone();
  34648. this.updateBoundingInfo(true, null);
  34649. },
  34650. enumerable: true,
  34651. configurable: true
  34652. });
  34653. /**
  34654. * Static function used to attach a new empty geometry to a mesh
  34655. * @param mesh defines the mesh to attach the geometry to
  34656. * @returns the new {BABYLON.Geometry}
  34657. */
  34658. Geometry.CreateGeometryForMesh = function (mesh) {
  34659. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34660. geometry.applyToMesh(mesh);
  34661. return geometry;
  34662. };
  34663. Object.defineProperty(Geometry.prototype, "extend", {
  34664. /**
  34665. * Gets the current extend of the geometry
  34666. */
  34667. get: function () {
  34668. return this._extend;
  34669. },
  34670. enumerable: true,
  34671. configurable: true
  34672. });
  34673. /**
  34674. * Gets the hosting scene
  34675. * @returns the hosting {BABYLON.Scene}
  34676. */
  34677. Geometry.prototype.getScene = function () {
  34678. return this._scene;
  34679. };
  34680. /**
  34681. * Gets the hosting engine
  34682. * @returns the hosting {BABYLON.Engine}
  34683. */
  34684. Geometry.prototype.getEngine = function () {
  34685. return this._engine;
  34686. };
  34687. /**
  34688. * Defines if the geometry is ready to use
  34689. * @returns true if the geometry is ready to be used
  34690. */
  34691. Geometry.prototype.isReady = function () {
  34692. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34693. };
  34694. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34695. /**
  34696. * Gets a value indicating that the geometry should not be serialized
  34697. */
  34698. get: function () {
  34699. for (var index = 0; index < this._meshes.length; index++) {
  34700. if (!this._meshes[index].doNotSerialize) {
  34701. return false;
  34702. }
  34703. }
  34704. return true;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. /** @ignore */
  34710. Geometry.prototype._rebuild = function () {
  34711. if (this._vertexArrayObjects) {
  34712. this._vertexArrayObjects = {};
  34713. }
  34714. // Index buffer
  34715. if (this._meshes.length !== 0 && this._indices) {
  34716. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34717. }
  34718. // Vertex buffers
  34719. for (var key in this._vertexBuffers) {
  34720. var vertexBuffer = this._vertexBuffers[key];
  34721. vertexBuffer._rebuild();
  34722. }
  34723. };
  34724. /**
  34725. * Affects all gemetry data in one call
  34726. * @param vertexData defines the geometry data
  34727. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34728. */
  34729. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34730. vertexData.applyToGeometry(this, updatable);
  34731. this.notifyUpdate();
  34732. };
  34733. /**
  34734. * Set specific vertex data
  34735. * @param kind defines the data kind (Position, normal, etc...)
  34736. * @param data defines the vertex data to use
  34737. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34738. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34739. */
  34740. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34741. if (updatable === void 0) { updatable = false; }
  34742. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34743. this.setVerticesBuffer(buffer);
  34744. };
  34745. /**
  34746. * Removes a specific vertex data
  34747. * @param kind defines the data kind (Position, normal, etc...)
  34748. */
  34749. Geometry.prototype.removeVerticesData = function (kind) {
  34750. if (this._vertexBuffers[kind]) {
  34751. this._vertexBuffers[kind].dispose();
  34752. delete this._vertexBuffers[kind];
  34753. }
  34754. };
  34755. /**
  34756. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34757. * @param buffer defines the vertex buffer to use
  34758. */
  34759. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34760. var kind = buffer.getKind();
  34761. if (this._vertexBuffers[kind]) {
  34762. this._vertexBuffers[kind].dispose();
  34763. }
  34764. this._vertexBuffers[kind] = buffer;
  34765. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34766. var data = buffer.getData();
  34767. var stride = buffer.getStrideSize();
  34768. this._totalVertices = data.length / stride;
  34769. this.updateExtend(data, stride);
  34770. this._resetPointsArrayCache();
  34771. var meshes = this._meshes;
  34772. var numOfMeshes = meshes.length;
  34773. for (var index = 0; index < numOfMeshes; index++) {
  34774. var mesh = meshes[index];
  34775. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34776. mesh._createGlobalSubMesh(false);
  34777. mesh.computeWorldMatrix(true);
  34778. }
  34779. }
  34780. this.notifyUpdate(kind);
  34781. if (this._vertexArrayObjects) {
  34782. this._disposeVertexArrayObjects();
  34783. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34784. }
  34785. };
  34786. /**
  34787. * Update a specific vertex buffer
  34788. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34789. * It will do nothing if the buffer is not updatable
  34790. * @param kind defines the data kind (Position, normal, etc...)
  34791. * @param data defines the data to use
  34792. * @param offset defines the offset in the target buffer where to store the data
  34793. */
  34794. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34795. var vertexBuffer = this.getVertexBuffer(kind);
  34796. if (!vertexBuffer) {
  34797. return;
  34798. }
  34799. vertexBuffer.updateDirectly(data, offset);
  34800. this.notifyUpdate(kind);
  34801. };
  34802. /**
  34803. * Update a specific vertex buffer
  34804. * This function will create a new buffer if the current one is not updatable
  34805. * @param kind defines the data kind (Position, normal, etc...)
  34806. * @param data defines the data to use
  34807. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34808. */
  34809. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34810. if (updateExtends === void 0) { updateExtends = false; }
  34811. var vertexBuffer = this.getVertexBuffer(kind);
  34812. if (!vertexBuffer) {
  34813. return;
  34814. }
  34815. vertexBuffer.update(data);
  34816. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34817. var stride = vertexBuffer.getStrideSize();
  34818. this._totalVertices = data.length / stride;
  34819. this.updateBoundingInfo(updateExtends, data);
  34820. }
  34821. this.notifyUpdate(kind);
  34822. };
  34823. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34824. if (updateExtends) {
  34825. this.updateExtend(data);
  34826. }
  34827. var meshes = this._meshes;
  34828. var numOfMeshes = meshes.length;
  34829. this._resetPointsArrayCache();
  34830. for (var index = 0; index < numOfMeshes; index++) {
  34831. var mesh = meshes[index];
  34832. if (updateExtends) {
  34833. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34834. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34835. var subMesh = mesh.subMeshes[subIndex];
  34836. subMesh.refreshBoundingInfo();
  34837. }
  34838. }
  34839. }
  34840. };
  34841. /** @ignore */
  34842. Geometry.prototype._bind = function (effect, indexToBind) {
  34843. if (!effect) {
  34844. return;
  34845. }
  34846. if (indexToBind === undefined) {
  34847. indexToBind = this._indexBuffer;
  34848. }
  34849. var vbs = this.getVertexBuffers();
  34850. if (!vbs) {
  34851. return;
  34852. }
  34853. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34854. this._engine.bindBuffers(vbs, indexToBind, effect);
  34855. return;
  34856. }
  34857. // Using VAO
  34858. if (!this._vertexArrayObjects[effect.key]) {
  34859. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34860. }
  34861. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34862. };
  34863. /**
  34864. * Gets total number of vertices
  34865. * @returns the total number of vertices
  34866. */
  34867. Geometry.prototype.getTotalVertices = function () {
  34868. if (!this.isReady()) {
  34869. return 0;
  34870. }
  34871. return this._totalVertices;
  34872. };
  34873. /**
  34874. * Gets a specific vertex data attached to this geometry
  34875. * @param kind defines the data kind (Position, normal, etc...)
  34876. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34877. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34878. * @returns a float array containing vertex data
  34879. */
  34880. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34881. var vertexBuffer = this.getVertexBuffer(kind);
  34882. if (!vertexBuffer) {
  34883. return null;
  34884. }
  34885. var orig = vertexBuffer.getData();
  34886. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34887. return orig;
  34888. }
  34889. else {
  34890. var len = orig.length;
  34891. var copy = [];
  34892. for (var i = 0; i < len; i++) {
  34893. copy.push(orig[i]);
  34894. }
  34895. return copy;
  34896. }
  34897. };
  34898. /**
  34899. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34900. * @param kind defines the data kind (Position, normal, etc...)
  34901. * @returns true if the vertex buffer with the specified kind is updatable
  34902. */
  34903. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34904. var vb = this._vertexBuffers[kind];
  34905. if (!vb) {
  34906. return false;
  34907. }
  34908. return vb.isUpdatable();
  34909. };
  34910. /**
  34911. * Gets a specific vertex buffer
  34912. * @param kind defines the data kind (Position, normal, etc...)
  34913. * @returns a {BABYLON.VertexBuffer}
  34914. */
  34915. Geometry.prototype.getVertexBuffer = function (kind) {
  34916. if (!this.isReady()) {
  34917. return null;
  34918. }
  34919. return this._vertexBuffers[kind];
  34920. };
  34921. /**
  34922. * Returns all vertex buffers
  34923. * @return an object holding all vertex buffers indexed by kind
  34924. */
  34925. Geometry.prototype.getVertexBuffers = function () {
  34926. if (!this.isReady()) {
  34927. return null;
  34928. }
  34929. return this._vertexBuffers;
  34930. };
  34931. /**
  34932. * Gets a boolean indicating if specific vertex buffer is present
  34933. * @param kind defines the data kind (Position, normal, etc...)
  34934. * @returns true if data is present
  34935. */
  34936. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34937. if (!this._vertexBuffers) {
  34938. if (this._delayInfo) {
  34939. return this._delayInfo.indexOf(kind) !== -1;
  34940. }
  34941. return false;
  34942. }
  34943. return this._vertexBuffers[kind] !== undefined;
  34944. };
  34945. /**
  34946. * Gets a list of all attached data kinds (Position, normal, etc...)
  34947. * @returns a list of string containing all kinds
  34948. */
  34949. Geometry.prototype.getVerticesDataKinds = function () {
  34950. var result = [];
  34951. var kind;
  34952. if (!this._vertexBuffers && this._delayInfo) {
  34953. for (kind in this._delayInfo) {
  34954. result.push(kind);
  34955. }
  34956. }
  34957. else {
  34958. for (kind in this._vertexBuffers) {
  34959. result.push(kind);
  34960. }
  34961. }
  34962. return result;
  34963. };
  34964. /**
  34965. * Update index buffer
  34966. * @param indices defines the indices to store in the index buffer
  34967. * @param offset defines the offset in the target buffer where to store the data
  34968. */
  34969. Geometry.prototype.updateIndices = function (indices, offset) {
  34970. if (!this._indexBuffer) {
  34971. return;
  34972. }
  34973. if (!this._indexBufferIsUpdatable) {
  34974. this.setIndices(indices, null, true);
  34975. }
  34976. else {
  34977. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34978. }
  34979. };
  34980. /**
  34981. * Creates a new index buffer
  34982. * @param indices defines the indices to store in the index buffer
  34983. * @param totalVertices defines the total number of vertices (could be null)
  34984. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34985. */
  34986. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34987. if (totalVertices === void 0) { totalVertices = null; }
  34988. if (updatable === void 0) { updatable = false; }
  34989. if (this._indexBuffer) {
  34990. this._engine._releaseBuffer(this._indexBuffer);
  34991. }
  34992. this._disposeVertexArrayObjects();
  34993. this._indices = indices;
  34994. this._indexBufferIsUpdatable = updatable;
  34995. if (this._meshes.length !== 0 && this._indices) {
  34996. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34997. }
  34998. if (totalVertices != undefined) {
  34999. this._totalVertices = totalVertices;
  35000. }
  35001. var meshes = this._meshes;
  35002. var numOfMeshes = meshes.length;
  35003. for (var index = 0; index < numOfMeshes; index++) {
  35004. meshes[index]._createGlobalSubMesh(true);
  35005. }
  35006. this.notifyUpdate();
  35007. };
  35008. /**
  35009. * Return the total number of indices
  35010. * @returns the total number of indices
  35011. */
  35012. Geometry.prototype.getTotalIndices = function () {
  35013. if (!this.isReady()) {
  35014. return 0;
  35015. }
  35016. return this._indices.length;
  35017. };
  35018. /**
  35019. * Gets the index buffer array
  35020. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35021. * @returns the index buffer array
  35022. */
  35023. Geometry.prototype.getIndices = function (copyWhenShared) {
  35024. if (!this.isReady()) {
  35025. return null;
  35026. }
  35027. var orig = this._indices;
  35028. if (!copyWhenShared || this._meshes.length === 1) {
  35029. return orig;
  35030. }
  35031. else {
  35032. var len = orig.length;
  35033. var copy = [];
  35034. for (var i = 0; i < len; i++) {
  35035. copy.push(orig[i]);
  35036. }
  35037. return copy;
  35038. }
  35039. };
  35040. /**
  35041. * Gets the index buffer
  35042. * @return the index buffer
  35043. */
  35044. Geometry.prototype.getIndexBuffer = function () {
  35045. if (!this.isReady()) {
  35046. return null;
  35047. }
  35048. return this._indexBuffer;
  35049. };
  35050. /** @ignore */
  35051. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35052. if (effect === void 0) { effect = null; }
  35053. if (!effect || !this._vertexArrayObjects) {
  35054. return;
  35055. }
  35056. if (this._vertexArrayObjects[effect.key]) {
  35057. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35058. delete this._vertexArrayObjects[effect.key];
  35059. }
  35060. };
  35061. /**
  35062. * Release the associated resources for a specific mesh
  35063. * @param mesh defines the source mesh
  35064. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35065. */
  35066. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35067. var meshes = this._meshes;
  35068. var index = meshes.indexOf(mesh);
  35069. if (index === -1) {
  35070. return;
  35071. }
  35072. meshes.splice(index, 1);
  35073. mesh._geometry = null;
  35074. if (meshes.length === 0 && shouldDispose) {
  35075. this.dispose();
  35076. }
  35077. };
  35078. /**
  35079. * Apply current geometry to a given mesh
  35080. * @param mesh defines the mesh to apply geometry to
  35081. */
  35082. Geometry.prototype.applyToMesh = function (mesh) {
  35083. if (mesh._geometry === this) {
  35084. return;
  35085. }
  35086. var previousGeometry = mesh._geometry;
  35087. if (previousGeometry) {
  35088. previousGeometry.releaseForMesh(mesh);
  35089. }
  35090. var meshes = this._meshes;
  35091. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35092. mesh._geometry = this;
  35093. this._scene.pushGeometry(this);
  35094. meshes.push(mesh);
  35095. if (this.isReady()) {
  35096. this._applyToMesh(mesh);
  35097. }
  35098. else {
  35099. mesh._boundingInfo = this._boundingInfo;
  35100. }
  35101. };
  35102. Geometry.prototype.updateExtend = function (data, stride) {
  35103. if (data === void 0) { data = null; }
  35104. if (!data) {
  35105. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35106. }
  35107. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35108. };
  35109. Geometry.prototype._applyToMesh = function (mesh) {
  35110. var numOfMeshes = this._meshes.length;
  35111. // vertexBuffers
  35112. for (var kind in this._vertexBuffers) {
  35113. if (numOfMeshes === 1) {
  35114. this._vertexBuffers[kind].create();
  35115. }
  35116. var buffer = this._vertexBuffers[kind].getBuffer();
  35117. if (buffer)
  35118. buffer.references = numOfMeshes;
  35119. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35120. if (!this._extend) {
  35121. this.updateExtend(this._vertexBuffers[kind].getData());
  35122. }
  35123. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35124. mesh._createGlobalSubMesh(false);
  35125. //bounding info was just created again, world matrix should be applied again.
  35126. mesh._updateBoundingInfo();
  35127. }
  35128. }
  35129. // indexBuffer
  35130. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35131. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35132. }
  35133. if (this._indexBuffer) {
  35134. this._indexBuffer.references = numOfMeshes;
  35135. }
  35136. };
  35137. Geometry.prototype.notifyUpdate = function (kind) {
  35138. if (this.onGeometryUpdated) {
  35139. this.onGeometryUpdated(this, kind);
  35140. }
  35141. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35142. var mesh = _a[_i];
  35143. mesh._markSubMeshesAsAttributesDirty();
  35144. }
  35145. };
  35146. /**
  35147. * Load the geometry if it was flagged as delay loaded
  35148. * @param scene defines the hosting scene
  35149. * @param onLoaded defines a callback called when the geometry is loaded
  35150. */
  35151. Geometry.prototype.load = function (scene, onLoaded) {
  35152. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35153. return;
  35154. }
  35155. if (this.isReady()) {
  35156. if (onLoaded) {
  35157. onLoaded();
  35158. }
  35159. return;
  35160. }
  35161. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35162. this._queueLoad(scene, onLoaded);
  35163. };
  35164. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35165. var _this = this;
  35166. if (!this.delayLoadingFile) {
  35167. return;
  35168. }
  35169. scene._addPendingData(this);
  35170. scene._loadFile(this.delayLoadingFile, function (data) {
  35171. if (!_this._delayLoadingFunction) {
  35172. return;
  35173. }
  35174. _this._delayLoadingFunction(JSON.parse(data), _this);
  35175. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35176. _this._delayInfo = [];
  35177. scene._removePendingData(_this);
  35178. var meshes = _this._meshes;
  35179. var numOfMeshes = meshes.length;
  35180. for (var index = 0; index < numOfMeshes; index++) {
  35181. _this._applyToMesh(meshes[index]);
  35182. }
  35183. if (onLoaded) {
  35184. onLoaded();
  35185. }
  35186. }, undefined, true);
  35187. };
  35188. /**
  35189. * Invert the geometry to move from a right handed system to a left handed one.
  35190. */
  35191. Geometry.prototype.toLeftHanded = function () {
  35192. // Flip faces
  35193. var tIndices = this.getIndices(false);
  35194. if (tIndices != null && tIndices.length > 0) {
  35195. for (var i = 0; i < tIndices.length; i += 3) {
  35196. var tTemp = tIndices[i + 0];
  35197. tIndices[i + 0] = tIndices[i + 2];
  35198. tIndices[i + 2] = tTemp;
  35199. }
  35200. this.setIndices(tIndices);
  35201. }
  35202. // Negate position.z
  35203. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35204. if (tPositions != null && tPositions.length > 0) {
  35205. for (var i = 0; i < tPositions.length; i += 3) {
  35206. tPositions[i + 2] = -tPositions[i + 2];
  35207. }
  35208. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35209. }
  35210. // Negate normal.z
  35211. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35212. if (tNormals != null && tNormals.length > 0) {
  35213. for (var i = 0; i < tNormals.length; i += 3) {
  35214. tNormals[i + 2] = -tNormals[i + 2];
  35215. }
  35216. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35217. }
  35218. };
  35219. // Cache
  35220. /** @ignore */
  35221. Geometry.prototype._resetPointsArrayCache = function () {
  35222. this._positions = null;
  35223. };
  35224. /** @ignore */
  35225. Geometry.prototype._generatePointsArray = function () {
  35226. if (this._positions)
  35227. return true;
  35228. this._positions = [];
  35229. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35230. if (!data) {
  35231. return false;
  35232. }
  35233. for (var index = 0; index < data.length; index += 3) {
  35234. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35235. }
  35236. return true;
  35237. };
  35238. /**
  35239. * Gets a value indicating if the geometry is disposed
  35240. * @returns true if the geometry was disposed
  35241. */
  35242. Geometry.prototype.isDisposed = function () {
  35243. return this._isDisposed;
  35244. };
  35245. Geometry.prototype._disposeVertexArrayObjects = function () {
  35246. if (this._vertexArrayObjects) {
  35247. for (var kind in this._vertexArrayObjects) {
  35248. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35249. }
  35250. this._vertexArrayObjects = {};
  35251. }
  35252. };
  35253. /**
  35254. * Free all associated resources
  35255. */
  35256. Geometry.prototype.dispose = function () {
  35257. var meshes = this._meshes;
  35258. var numOfMeshes = meshes.length;
  35259. var index;
  35260. for (index = 0; index < numOfMeshes; index++) {
  35261. this.releaseForMesh(meshes[index]);
  35262. }
  35263. this._meshes = [];
  35264. this._disposeVertexArrayObjects();
  35265. for (var kind in this._vertexBuffers) {
  35266. this._vertexBuffers[kind].dispose();
  35267. }
  35268. this._vertexBuffers = {};
  35269. this._totalVertices = 0;
  35270. if (this._indexBuffer) {
  35271. this._engine._releaseBuffer(this._indexBuffer);
  35272. }
  35273. this._indexBuffer = null;
  35274. this._indices = [];
  35275. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35276. this.delayLoadingFile = null;
  35277. this._delayLoadingFunction = null;
  35278. this._delayInfo = [];
  35279. this._boundingInfo = null;
  35280. this._scene.removeGeometry(this);
  35281. this._isDisposed = true;
  35282. };
  35283. /**
  35284. * Clone the current geometry into a new geometry
  35285. * @param id defines the unique ID of the new geometry
  35286. * @returns a new geometry object
  35287. */
  35288. Geometry.prototype.copy = function (id) {
  35289. var vertexData = new BABYLON.VertexData();
  35290. vertexData.indices = [];
  35291. var indices = this.getIndices();
  35292. if (indices) {
  35293. for (var index = 0; index < indices.length; index++) {
  35294. vertexData.indices.push(indices[index]);
  35295. }
  35296. }
  35297. var updatable = false;
  35298. var stopChecking = false;
  35299. var kind;
  35300. for (kind in this._vertexBuffers) {
  35301. // using slice() to make a copy of the array and not just reference it
  35302. var data = this.getVerticesData(kind);
  35303. if (data instanceof Float32Array) {
  35304. vertexData.set(new Float32Array(data), kind);
  35305. }
  35306. else {
  35307. vertexData.set(data.slice(0), kind);
  35308. }
  35309. if (!stopChecking) {
  35310. var vb = this.getVertexBuffer(kind);
  35311. if (vb) {
  35312. updatable = vb.isUpdatable();
  35313. stopChecking = !updatable;
  35314. }
  35315. }
  35316. }
  35317. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35318. geometry.delayLoadState = this.delayLoadState;
  35319. geometry.delayLoadingFile = this.delayLoadingFile;
  35320. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35321. for (kind in this._delayInfo) {
  35322. geometry._delayInfo = geometry._delayInfo || [];
  35323. geometry._delayInfo.push(kind);
  35324. }
  35325. // Bounding info
  35326. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35327. return geometry;
  35328. };
  35329. /**
  35330. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35331. * @return a JSON representation of the current geometry data (without the vertices data)
  35332. */
  35333. Geometry.prototype.serialize = function () {
  35334. var serializationObject = {};
  35335. serializationObject.id = this.id;
  35336. serializationObject.updatable = this._updatable;
  35337. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35338. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35339. }
  35340. return serializationObject;
  35341. };
  35342. Geometry.prototype.toNumberArray = function (origin) {
  35343. if (Array.isArray(origin)) {
  35344. return origin;
  35345. }
  35346. else {
  35347. return Array.prototype.slice.call(origin);
  35348. }
  35349. };
  35350. /**
  35351. * Serialize all vertices data into a JSON oject
  35352. * @returns a JSON representation of the current geometry data
  35353. */
  35354. Geometry.prototype.serializeVerticeData = function () {
  35355. var serializationObject = this.serialize();
  35356. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35357. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35358. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35359. serializationObject.positions._updatable = true;
  35360. }
  35361. }
  35362. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35363. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35364. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35365. serializationObject.normals._updatable = true;
  35366. }
  35367. }
  35368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35369. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35370. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35371. serializationObject.tangets._updatable = true;
  35372. }
  35373. }
  35374. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35375. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35376. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35377. serializationObject.uvs._updatable = true;
  35378. }
  35379. }
  35380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35381. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35382. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35383. serializationObject.uv2s._updatable = true;
  35384. }
  35385. }
  35386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35387. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35388. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35389. serializationObject.uv3s._updatable = true;
  35390. }
  35391. }
  35392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35393. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35394. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35395. serializationObject.uv4s._updatable = true;
  35396. }
  35397. }
  35398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35399. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35400. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35401. serializationObject.uv5s._updatable = true;
  35402. }
  35403. }
  35404. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35405. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35406. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35407. serializationObject.uv6s._updatable = true;
  35408. }
  35409. }
  35410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35411. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35412. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35413. serializationObject.colors._updatable = true;
  35414. }
  35415. }
  35416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35417. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35418. serializationObject.matricesIndices._isExpanded = true;
  35419. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35420. serializationObject.matricesIndices._updatable = true;
  35421. }
  35422. }
  35423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35424. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35425. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35426. serializationObject.matricesWeights._updatable = true;
  35427. }
  35428. }
  35429. serializationObject.indices = this.toNumberArray(this.getIndices());
  35430. return serializationObject;
  35431. };
  35432. // Statics
  35433. /**
  35434. * Extracts a clone of a mesh geometry
  35435. * @param mesh defines the source mesh
  35436. * @param id defines the unique ID of the new geometry object
  35437. * @returns the new geometry object
  35438. */
  35439. Geometry.ExtractFromMesh = function (mesh, id) {
  35440. var geometry = mesh._geometry;
  35441. if (!geometry) {
  35442. return null;
  35443. }
  35444. return geometry.copy(id);
  35445. };
  35446. /**
  35447. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35448. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35449. * Be aware Math.random() could cause collisions, but:
  35450. * "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"
  35451. * @returns a string containing a new GUID
  35452. */
  35453. Geometry.RandomId = function () {
  35454. return BABYLON.Tools.RandomId();
  35455. };
  35456. /** @ignore */
  35457. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35458. var scene = mesh.getScene();
  35459. // Geometry
  35460. var geometryId = parsedGeometry.geometryId;
  35461. if (geometryId) {
  35462. var geometry = scene.getGeometryByID(geometryId);
  35463. if (geometry) {
  35464. geometry.applyToMesh(mesh);
  35465. }
  35466. }
  35467. else if (parsedGeometry instanceof ArrayBuffer) {
  35468. var binaryInfo = mesh._binaryInfo;
  35469. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35470. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35471. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35472. }
  35473. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35474. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35475. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35476. }
  35477. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35478. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35479. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35480. }
  35481. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35482. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35483. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35484. }
  35485. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35486. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35487. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35488. }
  35489. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35490. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35491. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35492. }
  35493. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35494. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35495. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35496. }
  35497. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35498. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35499. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35500. }
  35501. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35502. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35503. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35504. }
  35505. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35506. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35507. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35508. }
  35509. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35510. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35511. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35512. }
  35513. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35514. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35515. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35516. }
  35517. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35518. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35519. mesh.setIndices(indicesData, null);
  35520. }
  35521. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35522. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35523. mesh.subMeshes = [];
  35524. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35525. var materialIndex = subMeshesData[(i * 5) + 0];
  35526. var verticesStart = subMeshesData[(i * 5) + 1];
  35527. var verticesCount = subMeshesData[(i * 5) + 2];
  35528. var indexStart = subMeshesData[(i * 5) + 3];
  35529. var indexCount = subMeshesData[(i * 5) + 4];
  35530. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35531. }
  35532. }
  35533. }
  35534. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35535. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35536. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35537. if (parsedGeometry.tangents) {
  35538. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35539. }
  35540. if (parsedGeometry.uvs) {
  35541. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35542. }
  35543. if (parsedGeometry.uvs2) {
  35544. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35545. }
  35546. if (parsedGeometry.uvs3) {
  35547. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35548. }
  35549. if (parsedGeometry.uvs4) {
  35550. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35551. }
  35552. if (parsedGeometry.uvs5) {
  35553. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35554. }
  35555. if (parsedGeometry.uvs6) {
  35556. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35557. }
  35558. if (parsedGeometry.colors) {
  35559. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35560. }
  35561. if (parsedGeometry.matricesIndices) {
  35562. if (!parsedGeometry.matricesIndices._isExpanded) {
  35563. var floatIndices = [];
  35564. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35565. var matricesIndex = parsedGeometry.matricesIndices[i];
  35566. floatIndices.push(matricesIndex & 0x000000FF);
  35567. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35568. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35569. floatIndices.push(matricesIndex >> 24);
  35570. }
  35571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35572. }
  35573. else {
  35574. delete parsedGeometry.matricesIndices._isExpanded;
  35575. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35576. }
  35577. }
  35578. if (parsedGeometry.matricesIndicesExtra) {
  35579. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35580. var floatIndices = [];
  35581. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35582. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35583. floatIndices.push(matricesIndex & 0x000000FF);
  35584. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35585. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35586. floatIndices.push(matricesIndex >> 24);
  35587. }
  35588. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35589. }
  35590. else {
  35591. delete parsedGeometry.matricesIndices._isExpanded;
  35592. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35593. }
  35594. }
  35595. if (parsedGeometry.matricesWeights) {
  35596. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35598. }
  35599. if (parsedGeometry.matricesWeightsExtra) {
  35600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35601. }
  35602. mesh.setIndices(parsedGeometry.indices, null);
  35603. }
  35604. // SubMeshes
  35605. if (parsedGeometry.subMeshes) {
  35606. mesh.subMeshes = [];
  35607. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35608. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35609. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35610. }
  35611. }
  35612. // Flat shading
  35613. if (mesh._shouldGenerateFlatShading) {
  35614. mesh.convertToFlatShadedMesh();
  35615. delete mesh._shouldGenerateFlatShading;
  35616. }
  35617. // Update
  35618. mesh.computeWorldMatrix(true);
  35619. // Octree
  35620. var sceneOctree = scene.selectionOctree;
  35621. if (sceneOctree !== undefined && sceneOctree !== null) {
  35622. sceneOctree.addMesh(mesh);
  35623. }
  35624. };
  35625. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35626. var epsilon = 1e-3;
  35627. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35628. return;
  35629. }
  35630. var noInfluenceBoneIndex = 0.0;
  35631. if (parsedGeometry.skeletonId > -1) {
  35632. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35633. if (!skeleton) {
  35634. return;
  35635. }
  35636. noInfluenceBoneIndex = skeleton.bones.length;
  35637. }
  35638. else {
  35639. return;
  35640. }
  35641. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35642. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35643. var matricesWeights = parsedGeometry.matricesWeights;
  35644. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35645. var influencers = parsedGeometry.numBoneInfluencer;
  35646. var size = matricesWeights.length;
  35647. for (var i = 0; i < size; i += 4) {
  35648. var weight = 0.0;
  35649. var firstZeroWeight = -1;
  35650. for (var j = 0; j < 4; j++) {
  35651. var w = matricesWeights[i + j];
  35652. weight += w;
  35653. if (w < epsilon && firstZeroWeight < 0) {
  35654. firstZeroWeight = j;
  35655. }
  35656. }
  35657. if (matricesWeightsExtra) {
  35658. for (var j = 0; j < 4; j++) {
  35659. var w = matricesWeightsExtra[i + j];
  35660. weight += w;
  35661. if (w < epsilon && firstZeroWeight < 0) {
  35662. firstZeroWeight = j + 4;
  35663. }
  35664. }
  35665. }
  35666. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35667. firstZeroWeight = influencers - 1;
  35668. }
  35669. if (weight > epsilon) {
  35670. var mweight = 1.0 / weight;
  35671. for (var j = 0; j < 4; j++) {
  35672. matricesWeights[i + j] *= mweight;
  35673. }
  35674. if (matricesWeightsExtra) {
  35675. for (var j = 0; j < 4; j++) {
  35676. matricesWeightsExtra[i + j] *= mweight;
  35677. }
  35678. }
  35679. }
  35680. else {
  35681. if (firstZeroWeight >= 4) {
  35682. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35683. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35684. }
  35685. else {
  35686. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35687. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35688. }
  35689. }
  35690. }
  35691. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35692. if (parsedGeometry.matricesWeightsExtra) {
  35693. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35694. }
  35695. };
  35696. /**
  35697. * Create a new geometry from persisted data (Using .babylon file format)
  35698. * @param parsedVertexData defines the persisted data
  35699. * @param scene defines the hosting scene
  35700. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35701. * @returns the new geometry object
  35702. */
  35703. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35704. if (scene.getGeometryByID(parsedVertexData.id)) {
  35705. return null; // null since geometry could be something else than a box...
  35706. }
  35707. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35708. if (BABYLON.Tags) {
  35709. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35710. }
  35711. if (parsedVertexData.delayLoadingFile) {
  35712. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35713. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35714. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35715. geometry._delayInfo = [];
  35716. if (parsedVertexData.hasUVs) {
  35717. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35718. }
  35719. if (parsedVertexData.hasUVs2) {
  35720. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35721. }
  35722. if (parsedVertexData.hasUVs3) {
  35723. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35724. }
  35725. if (parsedVertexData.hasUVs4) {
  35726. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35727. }
  35728. if (parsedVertexData.hasUVs5) {
  35729. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35730. }
  35731. if (parsedVertexData.hasUVs6) {
  35732. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35733. }
  35734. if (parsedVertexData.hasColors) {
  35735. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35736. }
  35737. if (parsedVertexData.hasMatricesIndices) {
  35738. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35739. }
  35740. if (parsedVertexData.hasMatricesWeights) {
  35741. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35742. }
  35743. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35744. }
  35745. else {
  35746. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35747. }
  35748. scene.pushGeometry(geometry, true);
  35749. return geometry;
  35750. };
  35751. return Geometry;
  35752. }());
  35753. BABYLON.Geometry = Geometry;
  35754. // Primitives
  35755. /// Abstract class
  35756. /**
  35757. * Abstract class used to provide common services for all typed geometries
  35758. */
  35759. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35760. __extends(_PrimitiveGeometry, _super);
  35761. /**
  35762. * Creates a new typed geometry
  35763. * @param id defines the unique ID of the geometry
  35764. * @param scene defines the hosting scene
  35765. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35766. * @param mesh defines the hosting mesh (can be null)
  35767. */
  35768. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35769. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35770. if (mesh === void 0) { mesh = null; }
  35771. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35772. _this._canBeRegenerated = _canBeRegenerated;
  35773. _this._beingRegenerated = true;
  35774. _this.regenerate();
  35775. _this._beingRegenerated = false;
  35776. return _this;
  35777. }
  35778. /**
  35779. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35780. * @returns true if the geometry can be regenerated
  35781. */
  35782. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35783. return this._canBeRegenerated;
  35784. };
  35785. /**
  35786. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35787. */
  35788. _PrimitiveGeometry.prototype.regenerate = function () {
  35789. if (!this._canBeRegenerated) {
  35790. return;
  35791. }
  35792. this._beingRegenerated = true;
  35793. this.setAllVerticesData(this._regenerateVertexData(), false);
  35794. this._beingRegenerated = false;
  35795. };
  35796. /**
  35797. * Clone the geometry
  35798. * @param id defines the unique ID of the new geometry
  35799. * @returns the new geometry
  35800. */
  35801. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35802. return _super.prototype.copy.call(this, id);
  35803. };
  35804. // overrides
  35805. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35806. if (!this._beingRegenerated) {
  35807. return;
  35808. }
  35809. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35810. };
  35811. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35812. if (!this._beingRegenerated) {
  35813. return;
  35814. }
  35815. _super.prototype.setVerticesData.call(this, kind, data, false);
  35816. };
  35817. // to override
  35818. /** @ignore */
  35819. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35820. throw new Error("Abstract method");
  35821. };
  35822. _PrimitiveGeometry.prototype.copy = function (id) {
  35823. throw new Error("Must be overriden in sub-classes.");
  35824. };
  35825. _PrimitiveGeometry.prototype.serialize = function () {
  35826. var serializationObject = _super.prototype.serialize.call(this);
  35827. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35828. return serializationObject;
  35829. };
  35830. return _PrimitiveGeometry;
  35831. }(Geometry));
  35832. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35833. /**
  35834. * Creates a ribbon geometry
  35835. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35836. */
  35837. var RibbonGeometry = /** @class */ (function (_super) {
  35838. __extends(RibbonGeometry, _super);
  35839. /**
  35840. * Creates a ribbon geometry
  35841. * @param id defines the unique ID of the geometry
  35842. * @param scene defines the hosting scene
  35843. * @param pathArray defines the array of paths to use
  35844. * @param closeArray defines if the last path and the first path must be joined
  35845. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35846. * @param offset defines the offset between points
  35847. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35848. * @param mesh defines the hosting mesh (can be null)
  35849. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35850. */
  35851. function RibbonGeometry(id, scene,
  35852. /**
  35853. * Defines the array of paths to use
  35854. */
  35855. pathArray,
  35856. /**
  35857. * Defines if the last and first points of each path in your pathArray must be joined
  35858. */
  35859. closeArray,
  35860. /**
  35861. * Defines if the last and first points of each path in your pathArray must be joined
  35862. */
  35863. closePath,
  35864. /**
  35865. * Defines the offset between points
  35866. */
  35867. offset, canBeRegenerated, mesh,
  35868. /**
  35869. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35870. */
  35871. side) {
  35872. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35873. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35874. _this.pathArray = pathArray;
  35875. _this.closeArray = closeArray;
  35876. _this.closePath = closePath;
  35877. _this.offset = offset;
  35878. _this.side = side;
  35879. return _this;
  35880. }
  35881. /** @ignore */
  35882. RibbonGeometry.prototype._regenerateVertexData = function () {
  35883. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35884. };
  35885. RibbonGeometry.prototype.copy = function (id) {
  35886. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35887. };
  35888. return RibbonGeometry;
  35889. }(_PrimitiveGeometry));
  35890. BABYLON.RibbonGeometry = RibbonGeometry;
  35891. /**
  35892. * Creates a box geometry
  35893. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35894. */
  35895. var BoxGeometry = /** @class */ (function (_super) {
  35896. __extends(BoxGeometry, _super);
  35897. /**
  35898. * Creates a box geometry
  35899. * @param id defines the unique ID of the geometry
  35900. * @param scene defines the hosting scene
  35901. * @param size defines the zise of the box (width, height and depth are the same)
  35902. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35903. * @param mesh defines the hosting mesh (can be null)
  35904. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35905. */
  35906. function BoxGeometry(id, scene,
  35907. /**
  35908. * Defines the zise of the box (width, height and depth are the same)
  35909. */
  35910. size, canBeRegenerated, mesh,
  35911. /**
  35912. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35913. */
  35914. side) {
  35915. if (mesh === void 0) { mesh = null; }
  35916. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35917. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35918. _this.size = size;
  35919. _this.side = side;
  35920. return _this;
  35921. }
  35922. BoxGeometry.prototype._regenerateVertexData = function () {
  35923. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35924. };
  35925. BoxGeometry.prototype.copy = function (id) {
  35926. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35927. };
  35928. BoxGeometry.prototype.serialize = function () {
  35929. var serializationObject = _super.prototype.serialize.call(this);
  35930. serializationObject.size = this.size;
  35931. return serializationObject;
  35932. };
  35933. BoxGeometry.Parse = function (parsedBox, scene) {
  35934. if (scene.getGeometryByID(parsedBox.id)) {
  35935. return null; // null since geometry could be something else than a box...
  35936. }
  35937. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35938. if (BABYLON.Tags) {
  35939. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35940. }
  35941. scene.pushGeometry(box, true);
  35942. return box;
  35943. };
  35944. return BoxGeometry;
  35945. }(_PrimitiveGeometry));
  35946. BABYLON.BoxGeometry = BoxGeometry;
  35947. /**
  35948. * Creates a sphere geometry
  35949. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35950. */
  35951. var SphereGeometry = /** @class */ (function (_super) {
  35952. __extends(SphereGeometry, _super);
  35953. /**
  35954. * Create a new sphere geometry
  35955. * @param id defines the unique ID of the geometry
  35956. * @param scene defines the hosting scene
  35957. * @param segments defines the number of segments to use to create the sphere
  35958. * @param diameter defines the diameter of the sphere
  35959. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35960. * @param mesh defines the hosting mesh (can be null)
  35961. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35962. */
  35963. function SphereGeometry(id, scene,
  35964. /**
  35965. * Defines the number of segments to use to create the sphere
  35966. */
  35967. segments,
  35968. /**
  35969. * Defines the diameter of the sphere
  35970. */
  35971. diameter, canBeRegenerated, mesh,
  35972. /**
  35973. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35974. */
  35975. side) {
  35976. if (mesh === void 0) { mesh = null; }
  35977. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35978. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35979. _this.segments = segments;
  35980. _this.diameter = diameter;
  35981. _this.side = side;
  35982. return _this;
  35983. }
  35984. SphereGeometry.prototype._regenerateVertexData = function () {
  35985. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35986. };
  35987. SphereGeometry.prototype.copy = function (id) {
  35988. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35989. };
  35990. SphereGeometry.prototype.serialize = function () {
  35991. var serializationObject = _super.prototype.serialize.call(this);
  35992. serializationObject.segments = this.segments;
  35993. serializationObject.diameter = this.diameter;
  35994. return serializationObject;
  35995. };
  35996. SphereGeometry.Parse = function (parsedSphere, scene) {
  35997. if (scene.getGeometryByID(parsedSphere.id)) {
  35998. return null; // null since geometry could be something else than a sphere...
  35999. }
  36000. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36001. if (BABYLON.Tags) {
  36002. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36003. }
  36004. scene.pushGeometry(sphere, true);
  36005. return sphere;
  36006. };
  36007. return SphereGeometry;
  36008. }(_PrimitiveGeometry));
  36009. BABYLON.SphereGeometry = SphereGeometry;
  36010. /**
  36011. * Creates a disc geometry
  36012. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36013. */
  36014. var DiscGeometry = /** @class */ (function (_super) {
  36015. __extends(DiscGeometry, _super);
  36016. /**
  36017. * Creates a new disc geometry
  36018. * @param id defines the unique ID of the geometry
  36019. * @param scene defines the hosting scene
  36020. * @param radius defines the radius of the disc
  36021. * @param tessellation defines the tesselation factor to apply to the disc
  36022. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36023. * @param mesh defines the hosting mesh (can be null)
  36024. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36025. */
  36026. function DiscGeometry(id, scene,
  36027. /**
  36028. * Defines the radius of the disc
  36029. */
  36030. radius,
  36031. /**
  36032. * Defines the tesselation factor to apply to the disc
  36033. */
  36034. tessellation, canBeRegenerated, mesh,
  36035. /**
  36036. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36037. */
  36038. side) {
  36039. if (mesh === void 0) { mesh = null; }
  36040. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36041. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36042. _this.radius = radius;
  36043. _this.tessellation = tessellation;
  36044. _this.side = side;
  36045. return _this;
  36046. }
  36047. DiscGeometry.prototype._regenerateVertexData = function () {
  36048. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36049. };
  36050. DiscGeometry.prototype.copy = function (id) {
  36051. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36052. };
  36053. return DiscGeometry;
  36054. }(_PrimitiveGeometry));
  36055. BABYLON.DiscGeometry = DiscGeometry;
  36056. /**
  36057. * Creates a new cylinder geometry
  36058. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36059. */
  36060. var CylinderGeometry = /** @class */ (function (_super) {
  36061. __extends(CylinderGeometry, _super);
  36062. /**
  36063. * Creates a new cylinder geometry
  36064. * @param id defines the unique ID of the geometry
  36065. * @param scene defines the hosting scene
  36066. * @param height defines the height of the cylinder
  36067. * @param diameterTop defines the diameter of the cylinder's top cap
  36068. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36069. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36070. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36071. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36072. * @param mesh defines the hosting mesh (can be null)
  36073. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36074. */
  36075. function CylinderGeometry(id, scene,
  36076. /**
  36077. * Defines the height of the cylinder
  36078. */
  36079. height,
  36080. /**
  36081. * Defines the diameter of the cylinder's top cap
  36082. */
  36083. diameterTop,
  36084. /**
  36085. * Defines the diameter of the cylinder's bottom cap
  36086. */
  36087. diameterBottom,
  36088. /**
  36089. * Defines the tessellation factor to apply to the cylinder
  36090. */
  36091. tessellation,
  36092. /**
  36093. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36094. */
  36095. subdivisions, canBeRegenerated, mesh,
  36096. /**
  36097. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36098. */
  36099. side) {
  36100. if (subdivisions === void 0) { subdivisions = 1; }
  36101. if (mesh === void 0) { mesh = null; }
  36102. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36103. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36104. _this.height = height;
  36105. _this.diameterTop = diameterTop;
  36106. _this.diameterBottom = diameterBottom;
  36107. _this.tessellation = tessellation;
  36108. _this.subdivisions = subdivisions;
  36109. _this.side = side;
  36110. return _this;
  36111. }
  36112. CylinderGeometry.prototype._regenerateVertexData = function () {
  36113. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36114. };
  36115. CylinderGeometry.prototype.copy = function (id) {
  36116. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36117. };
  36118. CylinderGeometry.prototype.serialize = function () {
  36119. var serializationObject = _super.prototype.serialize.call(this);
  36120. serializationObject.height = this.height;
  36121. serializationObject.diameterTop = this.diameterTop;
  36122. serializationObject.diameterBottom = this.diameterBottom;
  36123. serializationObject.tessellation = this.tessellation;
  36124. return serializationObject;
  36125. };
  36126. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36127. if (scene.getGeometryByID(parsedCylinder.id)) {
  36128. return null; // null since geometry could be something else than a cylinder...
  36129. }
  36130. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36131. if (BABYLON.Tags) {
  36132. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36133. }
  36134. scene.pushGeometry(cylinder, true);
  36135. return cylinder;
  36136. };
  36137. return CylinderGeometry;
  36138. }(_PrimitiveGeometry));
  36139. BABYLON.CylinderGeometry = CylinderGeometry;
  36140. /**
  36141. * Creates a new torus geometry
  36142. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36143. */
  36144. var TorusGeometry = /** @class */ (function (_super) {
  36145. __extends(TorusGeometry, _super);
  36146. /**
  36147. * Creates a new torus geometry
  36148. * @param id defines the unique ID of the geometry
  36149. * @param scene defines the hosting scene
  36150. * @param diameter defines the diameter of the torus
  36151. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36152. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36153. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36154. * @param mesh defines the hosting mesh (can be null)
  36155. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36156. */
  36157. function TorusGeometry(id, scene,
  36158. /**
  36159. * Defines the diameter of the torus
  36160. */
  36161. diameter,
  36162. /**
  36163. * Defines the thickness of the torus (ie. internal diameter)
  36164. */
  36165. thickness,
  36166. /**
  36167. * Defines the tesselation factor to apply to the torus
  36168. */
  36169. tessellation, canBeRegenerated, mesh,
  36170. /**
  36171. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36172. */
  36173. side) {
  36174. if (mesh === void 0) { mesh = null; }
  36175. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36176. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36177. _this.diameter = diameter;
  36178. _this.thickness = thickness;
  36179. _this.tessellation = tessellation;
  36180. _this.side = side;
  36181. return _this;
  36182. }
  36183. TorusGeometry.prototype._regenerateVertexData = function () {
  36184. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36185. };
  36186. TorusGeometry.prototype.copy = function (id) {
  36187. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36188. };
  36189. TorusGeometry.prototype.serialize = function () {
  36190. var serializationObject = _super.prototype.serialize.call(this);
  36191. serializationObject.diameter = this.diameter;
  36192. serializationObject.thickness = this.thickness;
  36193. serializationObject.tessellation = this.tessellation;
  36194. return serializationObject;
  36195. };
  36196. TorusGeometry.Parse = function (parsedTorus, scene) {
  36197. if (scene.getGeometryByID(parsedTorus.id)) {
  36198. return null; // null since geometry could be something else than a torus...
  36199. }
  36200. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36201. if (BABYLON.Tags) {
  36202. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36203. }
  36204. scene.pushGeometry(torus, true);
  36205. return torus;
  36206. };
  36207. return TorusGeometry;
  36208. }(_PrimitiveGeometry));
  36209. BABYLON.TorusGeometry = TorusGeometry;
  36210. /**
  36211. * Creates a new ground geometry
  36212. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36213. */
  36214. var GroundGeometry = /** @class */ (function (_super) {
  36215. __extends(GroundGeometry, _super);
  36216. /**
  36217. * Creates a new ground geometry
  36218. * @param id defines the unique ID of the geometry
  36219. * @param scene defines the hosting scene
  36220. * @param width defines the width of the ground
  36221. * @param height defines the height of the ground
  36222. * @param subdivisions defines the subdivisions to apply to the ground
  36223. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36224. * @param mesh defines the hosting mesh (can be null)
  36225. */
  36226. function GroundGeometry(id, scene,
  36227. /**
  36228. * Defines the width of the ground
  36229. */
  36230. width,
  36231. /**
  36232. * Defines the height of the ground
  36233. */
  36234. height,
  36235. /**
  36236. * Defines the subdivisions to apply to the ground
  36237. */
  36238. subdivisions, canBeRegenerated, mesh) {
  36239. if (mesh === void 0) { mesh = null; }
  36240. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36241. _this.width = width;
  36242. _this.height = height;
  36243. _this.subdivisions = subdivisions;
  36244. return _this;
  36245. }
  36246. GroundGeometry.prototype._regenerateVertexData = function () {
  36247. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36248. };
  36249. GroundGeometry.prototype.copy = function (id) {
  36250. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36251. };
  36252. GroundGeometry.prototype.serialize = function () {
  36253. var serializationObject = _super.prototype.serialize.call(this);
  36254. serializationObject.width = this.width;
  36255. serializationObject.height = this.height;
  36256. serializationObject.subdivisions = this.subdivisions;
  36257. return serializationObject;
  36258. };
  36259. GroundGeometry.Parse = function (parsedGround, scene) {
  36260. if (scene.getGeometryByID(parsedGround.id)) {
  36261. return null; // null since geometry could be something else than a ground...
  36262. }
  36263. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36264. if (BABYLON.Tags) {
  36265. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36266. }
  36267. scene.pushGeometry(ground, true);
  36268. return ground;
  36269. };
  36270. return GroundGeometry;
  36271. }(_PrimitiveGeometry));
  36272. BABYLON.GroundGeometry = GroundGeometry;
  36273. /**
  36274. * Creates a tiled ground geometry
  36275. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36276. */
  36277. var TiledGroundGeometry = /** @class */ (function (_super) {
  36278. __extends(TiledGroundGeometry, _super);
  36279. /**
  36280. * Creates a tiled ground geometry
  36281. * @param id defines the unique ID of the geometry
  36282. * @param scene defines the hosting scene
  36283. * @param xmin defines the minimum value on X axis
  36284. * @param zmin defines the minimum value on Z axis
  36285. * @param xmax defines the maximum value on X axis
  36286. * @param zmax defines the maximum value on Z axis
  36287. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36288. * @param precision defines the precision to use when computing the tiles
  36289. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36290. * @param mesh defines the hosting mesh (can be null)
  36291. */
  36292. function TiledGroundGeometry(id, scene,
  36293. /**
  36294. * Defines the minimum value on X axis
  36295. */
  36296. xmin,
  36297. /**
  36298. * Defines the minimum value on Z axis
  36299. */
  36300. zmin,
  36301. /**
  36302. * Defines the maximum value on X axis
  36303. */
  36304. xmax,
  36305. /**
  36306. * Defines the maximum value on Z axis
  36307. */
  36308. zmax,
  36309. /**
  36310. * Defines the subdivisions to apply to the ground
  36311. */
  36312. subdivisions,
  36313. /**
  36314. * Defines the precision to use when computing the tiles
  36315. */
  36316. precision, canBeRegenerated, mesh) {
  36317. if (mesh === void 0) { mesh = null; }
  36318. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36319. _this.xmin = xmin;
  36320. _this.zmin = zmin;
  36321. _this.xmax = xmax;
  36322. _this.zmax = zmax;
  36323. _this.subdivisions = subdivisions;
  36324. _this.precision = precision;
  36325. return _this;
  36326. }
  36327. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36328. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36329. };
  36330. TiledGroundGeometry.prototype.copy = function (id) {
  36331. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36332. };
  36333. return TiledGroundGeometry;
  36334. }(_PrimitiveGeometry));
  36335. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36336. /**
  36337. * Creates a plane geometry
  36338. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36339. */
  36340. var PlaneGeometry = /** @class */ (function (_super) {
  36341. __extends(PlaneGeometry, _super);
  36342. /**
  36343. * Creates a plane geometry
  36344. * @param id defines the unique ID of the geometry
  36345. * @param scene defines the hosting scene
  36346. * @param size defines the size of the plane (width === height)
  36347. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36348. * @param mesh defines the hosting mesh (can be null)
  36349. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36350. */
  36351. function PlaneGeometry(id, scene,
  36352. /**
  36353. * Defines the size of the plane (width === height)
  36354. */
  36355. size, canBeRegenerated, mesh,
  36356. /**
  36357. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36358. */
  36359. side) {
  36360. if (mesh === void 0) { mesh = null; }
  36361. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36362. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36363. _this.size = size;
  36364. _this.side = side;
  36365. return _this;
  36366. }
  36367. PlaneGeometry.prototype._regenerateVertexData = function () {
  36368. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36369. };
  36370. PlaneGeometry.prototype.copy = function (id) {
  36371. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36372. };
  36373. PlaneGeometry.prototype.serialize = function () {
  36374. var serializationObject = _super.prototype.serialize.call(this);
  36375. serializationObject.size = this.size;
  36376. return serializationObject;
  36377. };
  36378. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36379. if (scene.getGeometryByID(parsedPlane.id)) {
  36380. return null; // null since geometry could be something else than a ground...
  36381. }
  36382. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36383. if (BABYLON.Tags) {
  36384. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36385. }
  36386. scene.pushGeometry(plane, true);
  36387. return plane;
  36388. };
  36389. return PlaneGeometry;
  36390. }(_PrimitiveGeometry));
  36391. BABYLON.PlaneGeometry = PlaneGeometry;
  36392. /**
  36393. * Creates a torus knot geometry
  36394. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36395. */
  36396. var TorusKnotGeometry = /** @class */ (function (_super) {
  36397. __extends(TorusKnotGeometry, _super);
  36398. /**
  36399. * Creates a torus knot geometry
  36400. * @param id defines the unique ID of the geometry
  36401. * @param scene defines the hosting scene
  36402. * @param radius defines the radius of the torus knot
  36403. * @param tube defines the thickness of the torus knot tube
  36404. * @param radialSegments defines the number of radial segments
  36405. * @param tubularSegments defines the number of tubular segments
  36406. * @param p defines the first number of windings
  36407. * @param q defines the second number of windings
  36408. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36409. * @param mesh defines the hosting mesh (can be null)
  36410. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36411. */
  36412. function TorusKnotGeometry(id, scene,
  36413. /**
  36414. * Defines the radius of the torus knot
  36415. */
  36416. radius,
  36417. /**
  36418. * Defines the thickness of the torus knot tube
  36419. */
  36420. tube,
  36421. /**
  36422. * Defines the number of radial segments
  36423. */
  36424. radialSegments,
  36425. /**
  36426. * Defines the number of tubular segments
  36427. */
  36428. tubularSegments,
  36429. /**
  36430. * Defines the first number of windings
  36431. */
  36432. p,
  36433. /**
  36434. * Defines the second number of windings
  36435. */
  36436. q, canBeRegenerated, mesh,
  36437. /**
  36438. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36439. */
  36440. side) {
  36441. if (mesh === void 0) { mesh = null; }
  36442. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36443. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36444. _this.radius = radius;
  36445. _this.tube = tube;
  36446. _this.radialSegments = radialSegments;
  36447. _this.tubularSegments = tubularSegments;
  36448. _this.p = p;
  36449. _this.q = q;
  36450. _this.side = side;
  36451. return _this;
  36452. }
  36453. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36454. 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 });
  36455. };
  36456. TorusKnotGeometry.prototype.copy = function (id) {
  36457. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36458. };
  36459. TorusKnotGeometry.prototype.serialize = function () {
  36460. var serializationObject = _super.prototype.serialize.call(this);
  36461. serializationObject.radius = this.radius;
  36462. serializationObject.tube = this.tube;
  36463. serializationObject.radialSegments = this.radialSegments;
  36464. serializationObject.tubularSegments = this.tubularSegments;
  36465. serializationObject.p = this.p;
  36466. serializationObject.q = this.q;
  36467. return serializationObject;
  36468. };
  36469. ;
  36470. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36471. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36472. return null; // null since geometry could be something else than a ground...
  36473. }
  36474. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36475. if (BABYLON.Tags) {
  36476. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36477. }
  36478. scene.pushGeometry(torusKnot, true);
  36479. return torusKnot;
  36480. };
  36481. return TorusKnotGeometry;
  36482. }(_PrimitiveGeometry));
  36483. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36484. //}
  36485. })(BABYLON || (BABYLON = {}));
  36486. //# sourceMappingURL=babylon.geometry.js.map
  36487. var BABYLON;
  36488. (function (BABYLON) {
  36489. /**
  36490. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36491. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36492. */
  36493. var PostProcessManager = /** @class */ (function () {
  36494. /**
  36495. * Creates a new instance of @see PostProcess
  36496. * @param scene The scene that the post process is associated with.
  36497. */
  36498. function PostProcessManager(scene) {
  36499. this._vertexBuffers = {};
  36500. this._scene = scene;
  36501. }
  36502. PostProcessManager.prototype._prepareBuffers = function () {
  36503. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36504. return;
  36505. }
  36506. // VBO
  36507. var vertices = [];
  36508. vertices.push(1, 1);
  36509. vertices.push(-1, 1);
  36510. vertices.push(-1, -1);
  36511. vertices.push(1, -1);
  36512. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36513. this._buildIndexBuffer();
  36514. };
  36515. PostProcessManager.prototype._buildIndexBuffer = function () {
  36516. // Indices
  36517. var indices = [];
  36518. indices.push(0);
  36519. indices.push(1);
  36520. indices.push(2);
  36521. indices.push(0);
  36522. indices.push(2);
  36523. indices.push(3);
  36524. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36525. };
  36526. /**
  36527. * Rebuilds the vertex buffers of the manager.
  36528. */
  36529. PostProcessManager.prototype._rebuild = function () {
  36530. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36531. if (!vb) {
  36532. return;
  36533. }
  36534. vb._rebuild();
  36535. this._buildIndexBuffer();
  36536. };
  36537. // Methods
  36538. /**
  36539. * Prepares a frame to be run through a post process.
  36540. * @param sourceTexture The input texture to the post procesess. (default: null)
  36541. * @param postProcesses An array of post processes to be run. (default: null)
  36542. * @returns True if the post processes were able to be run.
  36543. */
  36544. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36545. if (sourceTexture === void 0) { sourceTexture = null; }
  36546. if (postProcesses === void 0) { postProcesses = null; }
  36547. var camera = this._scene.activeCamera;
  36548. if (!camera) {
  36549. return false;
  36550. }
  36551. var postProcesses = postProcesses || camera._postProcesses;
  36552. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36553. return false;
  36554. }
  36555. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36556. return true;
  36557. };
  36558. /**
  36559. * Manually render a set of post processes to a texture.
  36560. * @param postProcesses An array of post processes to be run.
  36561. * @param targetTexture The target texture to render to.
  36562. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36563. */
  36564. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36565. if (targetTexture === void 0) { targetTexture = null; }
  36566. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36567. var engine = this._scene.getEngine();
  36568. for (var index = 0; index < postProcesses.length; index++) {
  36569. if (index < postProcesses.length - 1) {
  36570. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36571. }
  36572. else {
  36573. if (targetTexture) {
  36574. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36575. }
  36576. else {
  36577. engine.restoreDefaultFramebuffer();
  36578. }
  36579. }
  36580. var pp = postProcesses[index];
  36581. var effect = pp.apply();
  36582. if (effect) {
  36583. pp.onBeforeRenderObservable.notifyObservers(effect);
  36584. // VBOs
  36585. this._prepareBuffers();
  36586. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36587. // Draw order
  36588. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36589. pp.onAfterRenderObservable.notifyObservers(effect);
  36590. }
  36591. }
  36592. // Restore depth buffer
  36593. engine.setDepthBuffer(true);
  36594. engine.setDepthWrite(true);
  36595. };
  36596. /**
  36597. * Finalize the result of the output of the postprocesses.
  36598. * @param doNotPresent If true the result will not be displayed to the screen.
  36599. * @param targetTexture The target texture to render to.
  36600. * @param faceIndex The index of the face to bind the target texture to.
  36601. * @param postProcesses The array of post processes to render.
  36602. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36603. */
  36604. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36605. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36606. var camera = this._scene.activeCamera;
  36607. if (!camera) {
  36608. return;
  36609. }
  36610. postProcesses = postProcesses || camera._postProcesses;
  36611. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36612. return;
  36613. }
  36614. var engine = this._scene.getEngine();
  36615. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36616. if (index < len - 1) {
  36617. postProcesses[index + 1].activate(camera, targetTexture);
  36618. }
  36619. else {
  36620. if (targetTexture) {
  36621. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36622. }
  36623. else {
  36624. engine.restoreDefaultFramebuffer();
  36625. }
  36626. }
  36627. if (doNotPresent) {
  36628. break;
  36629. }
  36630. var pp = postProcesses[index];
  36631. var effect = pp.apply();
  36632. if (effect) {
  36633. pp.onBeforeRenderObservable.notifyObservers(effect);
  36634. // VBOs
  36635. this._prepareBuffers();
  36636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36637. // Draw order
  36638. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36639. pp.onAfterRenderObservable.notifyObservers(effect);
  36640. }
  36641. }
  36642. // Restore states
  36643. engine.setDepthBuffer(true);
  36644. engine.setDepthWrite(true);
  36645. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36646. };
  36647. /**
  36648. * Disposes of the post process manager.
  36649. */
  36650. PostProcessManager.prototype.dispose = function () {
  36651. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36652. if (buffer) {
  36653. buffer.dispose();
  36654. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36655. }
  36656. if (this._indexBuffer) {
  36657. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36658. this._indexBuffer = null;
  36659. }
  36660. };
  36661. return PostProcessManager;
  36662. }());
  36663. BABYLON.PostProcessManager = PostProcessManager;
  36664. })(BABYLON || (BABYLON = {}));
  36665. //# sourceMappingURL=babylon.postProcessManager.js.map
  36666. var BABYLON;
  36667. (function (BABYLON) {
  36668. /**
  36669. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36670. */
  36671. var PerformanceMonitor = /** @class */ (function () {
  36672. /**
  36673. * constructor
  36674. * @param frameSampleSize The number of samples required to saturate the sliding window
  36675. */
  36676. function PerformanceMonitor(frameSampleSize) {
  36677. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36678. this._enabled = true;
  36679. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36680. }
  36681. /**
  36682. * Samples current frame
  36683. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36684. */
  36685. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36686. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36687. if (!this._enabled)
  36688. return;
  36689. if (this._lastFrameTimeMs != null) {
  36690. var dt = timeMs - this._lastFrameTimeMs;
  36691. this._rollingFrameTime.add(dt);
  36692. }
  36693. this._lastFrameTimeMs = timeMs;
  36694. };
  36695. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36696. /**
  36697. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36698. * @return Average frame time in milliseconds
  36699. */
  36700. get: function () {
  36701. return this._rollingFrameTime.average;
  36702. },
  36703. enumerable: true,
  36704. configurable: true
  36705. });
  36706. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36707. /**
  36708. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36709. * @return Frame time variance in milliseconds squared
  36710. */
  36711. get: function () {
  36712. return this._rollingFrameTime.variance;
  36713. },
  36714. enumerable: true,
  36715. configurable: true
  36716. });
  36717. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36718. /**
  36719. * Returns the frame time of the most recent frame
  36720. * @return Frame time in milliseconds
  36721. */
  36722. get: function () {
  36723. return this._rollingFrameTime.history(0);
  36724. },
  36725. enumerable: true,
  36726. configurable: true
  36727. });
  36728. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36729. /**
  36730. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36731. * @return Framerate in frames per second
  36732. */
  36733. get: function () {
  36734. return 1000.0 / this._rollingFrameTime.average;
  36735. },
  36736. enumerable: true,
  36737. configurable: true
  36738. });
  36739. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36740. /**
  36741. * Returns the average framerate in frames per second using the most recent frame time
  36742. * @return Framerate in frames per second
  36743. */
  36744. get: function () {
  36745. var history = this._rollingFrameTime.history(0);
  36746. if (history === 0) {
  36747. return 0;
  36748. }
  36749. return 1000.0 / history;
  36750. },
  36751. enumerable: true,
  36752. configurable: true
  36753. });
  36754. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36755. /**
  36756. * Returns true if enough samples have been taken to completely fill the sliding window
  36757. * @return true if saturated
  36758. */
  36759. get: function () {
  36760. return this._rollingFrameTime.isSaturated();
  36761. },
  36762. enumerable: true,
  36763. configurable: true
  36764. });
  36765. /**
  36766. * Enables contributions to the sliding window sample set
  36767. */
  36768. PerformanceMonitor.prototype.enable = function () {
  36769. this._enabled = true;
  36770. };
  36771. /**
  36772. * Disables contributions to the sliding window sample set
  36773. * Samples will not be interpolated over the disabled period
  36774. */
  36775. PerformanceMonitor.prototype.disable = function () {
  36776. this._enabled = false;
  36777. //clear last sample to avoid interpolating over the disabled period when next enabled
  36778. this._lastFrameTimeMs = null;
  36779. };
  36780. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36781. /**
  36782. * Returns true if sampling is enabled
  36783. * @return true if enabled
  36784. */
  36785. get: function () {
  36786. return this._enabled;
  36787. },
  36788. enumerable: true,
  36789. configurable: true
  36790. });
  36791. /**
  36792. * Resets performance monitor
  36793. */
  36794. PerformanceMonitor.prototype.reset = function () {
  36795. //clear last sample to avoid interpolating over the disabled period when next enabled
  36796. this._lastFrameTimeMs = null;
  36797. //wipe record
  36798. this._rollingFrameTime.reset();
  36799. };
  36800. return PerformanceMonitor;
  36801. }());
  36802. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36803. /**
  36804. * RollingAverage
  36805. *
  36806. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36807. */
  36808. var RollingAverage = /** @class */ (function () {
  36809. /**
  36810. * constructor
  36811. * @param length The number of samples required to saturate the sliding window
  36812. */
  36813. function RollingAverage(length) {
  36814. this._samples = new Array(length);
  36815. this.reset();
  36816. }
  36817. /**
  36818. * Adds a sample to the sample set
  36819. * @param v The sample value
  36820. */
  36821. RollingAverage.prototype.add = function (v) {
  36822. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36823. var delta;
  36824. //we need to check if we've already wrapped round
  36825. if (this.isSaturated()) {
  36826. //remove bottom of stack from mean
  36827. var bottomValue = this._samples[this._pos];
  36828. delta = bottomValue - this.average;
  36829. this.average -= delta / (this._sampleCount - 1);
  36830. this._m2 -= delta * (bottomValue - this.average);
  36831. }
  36832. else {
  36833. this._sampleCount++;
  36834. }
  36835. //add new value to mean
  36836. delta = v - this.average;
  36837. this.average += delta / (this._sampleCount);
  36838. this._m2 += delta * (v - this.average);
  36839. //set the new variance
  36840. this.variance = this._m2 / (this._sampleCount - 1);
  36841. this._samples[this._pos] = v;
  36842. this._pos++;
  36843. this._pos %= this._samples.length; //positive wrap around
  36844. };
  36845. /**
  36846. * Returns previously added values or null if outside of history or outside the sliding window domain
  36847. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36848. * @return Value previously recorded with add() or null if outside of range
  36849. */
  36850. RollingAverage.prototype.history = function (i) {
  36851. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36852. return 0;
  36853. }
  36854. var i0 = this._wrapPosition(this._pos - 1.0);
  36855. return this._samples[this._wrapPosition(i0 - i)];
  36856. };
  36857. /**
  36858. * Returns true if enough samples have been taken to completely fill the sliding window
  36859. * @return true if sample-set saturated
  36860. */
  36861. RollingAverage.prototype.isSaturated = function () {
  36862. return this._sampleCount >= this._samples.length;
  36863. };
  36864. /**
  36865. * Resets the rolling average (equivalent to 0 samples taken so far)
  36866. */
  36867. RollingAverage.prototype.reset = function () {
  36868. this.average = 0;
  36869. this.variance = 0;
  36870. this._sampleCount = 0;
  36871. this._pos = 0;
  36872. this._m2 = 0;
  36873. };
  36874. /**
  36875. * Wraps a value around the sample range boundaries
  36876. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36877. * @return Wrapped position in sample range
  36878. */
  36879. RollingAverage.prototype._wrapPosition = function (i) {
  36880. var max = this._samples.length;
  36881. return ((i % max) + max) % max;
  36882. };
  36883. return RollingAverage;
  36884. }());
  36885. BABYLON.RollingAverage = RollingAverage;
  36886. })(BABYLON || (BABYLON = {}));
  36887. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36888. var BABYLON;
  36889. (function (BABYLON) {
  36890. /**
  36891. * This groups together the common properties used for image processing either in direct forward pass
  36892. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36893. * or not.
  36894. */
  36895. var ImageProcessingConfiguration = /** @class */ (function () {
  36896. function ImageProcessingConfiguration() {
  36897. /**
  36898. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36899. */
  36900. this.colorCurves = new BABYLON.ColorCurves();
  36901. this._colorCurvesEnabled = false;
  36902. this._colorGradingEnabled = false;
  36903. this._colorGradingWithGreenDepth = true;
  36904. this._colorGradingBGR = true;
  36905. this._exposure = 1.0;
  36906. this._toneMappingEnabled = false;
  36907. this._contrast = 1.0;
  36908. /**
  36909. * Vignette stretch size.
  36910. */
  36911. this.vignetteStretch = 0;
  36912. /**
  36913. * Vignette centre X Offset.
  36914. */
  36915. this.vignetteCentreX = 0;
  36916. /**
  36917. * Vignette centre Y Offset.
  36918. */
  36919. this.vignetteCentreY = 0;
  36920. /**
  36921. * Vignette weight or intensity of the vignette effect.
  36922. */
  36923. this.vignetteWeight = 1.5;
  36924. /**
  36925. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36926. * if vignetteEnabled is set to true.
  36927. */
  36928. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36929. /**
  36930. * Camera field of view used by the Vignette effect.
  36931. */
  36932. this.vignetteCameraFov = 0.5;
  36933. this._grainEnabled = false;
  36934. this._grainIntensity = 30;
  36935. this._grainAnimated = false;
  36936. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36937. this._vignetteEnabled = false;
  36938. this._applyByPostProcess = false;
  36939. this._isEnabled = true;
  36940. /**
  36941. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36942. * @type {BABYLON.Observable}
  36943. */
  36944. this.onUpdateParameters = new BABYLON.Observable();
  36945. }
  36946. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36947. /**
  36948. * Gets wether the color curves effect is enabled.
  36949. */
  36950. get: function () {
  36951. return this._colorCurvesEnabled;
  36952. },
  36953. /**
  36954. * Sets wether the color curves effect is enabled.
  36955. */
  36956. set: function (value) {
  36957. if (this._colorCurvesEnabled === value) {
  36958. return;
  36959. }
  36960. this._colorCurvesEnabled = value;
  36961. this._updateParameters();
  36962. },
  36963. enumerable: true,
  36964. configurable: true
  36965. });
  36966. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36967. /**
  36968. * Gets wether the color grading effect is enabled.
  36969. */
  36970. get: function () {
  36971. return this._colorGradingEnabled;
  36972. },
  36973. /**
  36974. * Sets wether the color grading effect is enabled.
  36975. */
  36976. set: function (value) {
  36977. if (this._colorGradingEnabled === value) {
  36978. return;
  36979. }
  36980. this._colorGradingEnabled = value;
  36981. this._updateParameters();
  36982. },
  36983. enumerable: true,
  36984. configurable: true
  36985. });
  36986. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36987. /**
  36988. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36989. */
  36990. get: function () {
  36991. return this._colorGradingWithGreenDepth;
  36992. },
  36993. /**
  36994. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36995. */
  36996. set: function (value) {
  36997. if (this._colorGradingWithGreenDepth === value) {
  36998. return;
  36999. }
  37000. this._colorGradingWithGreenDepth = value;
  37001. this._updateParameters();
  37002. },
  37003. enumerable: true,
  37004. configurable: true
  37005. });
  37006. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37007. /**
  37008. * Gets wether the color grading texture contains BGR values.
  37009. */
  37010. get: function () {
  37011. return this._colorGradingBGR;
  37012. },
  37013. /**
  37014. * Sets wether the color grading texture contains BGR values.
  37015. */
  37016. set: function (value) {
  37017. if (this._colorGradingBGR === value) {
  37018. return;
  37019. }
  37020. this._colorGradingBGR = value;
  37021. this._updateParameters();
  37022. },
  37023. enumerable: true,
  37024. configurable: true
  37025. });
  37026. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37027. /**
  37028. * Gets the Exposure used in the effect.
  37029. */
  37030. get: function () {
  37031. return this._exposure;
  37032. },
  37033. /**
  37034. * Sets the Exposure used in the effect.
  37035. */
  37036. set: function (value) {
  37037. if (this._exposure === value) {
  37038. return;
  37039. }
  37040. this._exposure = value;
  37041. this._updateParameters();
  37042. },
  37043. enumerable: true,
  37044. configurable: true
  37045. });
  37046. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37047. /**
  37048. * Gets wether the tone mapping effect is enabled.
  37049. */
  37050. get: function () {
  37051. return this._toneMappingEnabled;
  37052. },
  37053. /**
  37054. * Sets wether the tone mapping effect is enabled.
  37055. */
  37056. set: function (value) {
  37057. if (this._toneMappingEnabled === value) {
  37058. return;
  37059. }
  37060. this._toneMappingEnabled = value;
  37061. this._updateParameters();
  37062. },
  37063. enumerable: true,
  37064. configurable: true
  37065. });
  37066. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37067. /**
  37068. * Gets the contrast used in the effect.
  37069. */
  37070. get: function () {
  37071. return this._contrast;
  37072. },
  37073. /**
  37074. * Sets the contrast used in the effect.
  37075. */
  37076. set: function (value) {
  37077. if (this._contrast === value) {
  37078. return;
  37079. }
  37080. this._contrast = value;
  37081. this._updateParameters();
  37082. },
  37083. enumerable: true,
  37084. configurable: true
  37085. });
  37086. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37087. /**
  37088. * If the grain effect should be enabled.
  37089. */
  37090. get: function () {
  37091. return this._grainEnabled;
  37092. },
  37093. set: function (value) {
  37094. if (this._grainEnabled === value) {
  37095. return;
  37096. }
  37097. this._grainEnabled = value;
  37098. this._updateParameters();
  37099. },
  37100. enumerable: true,
  37101. configurable: true
  37102. });
  37103. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37104. /**
  37105. * Amount of grain to be applied by the grain effect.
  37106. */
  37107. get: function () {
  37108. return this._grainIntensity;
  37109. },
  37110. set: function (value) {
  37111. if (this._grainIntensity === value) {
  37112. return;
  37113. }
  37114. this._grainIntensity = value;
  37115. },
  37116. enumerable: true,
  37117. configurable: true
  37118. });
  37119. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37120. /**
  37121. * If the grain effect should be animated.
  37122. */
  37123. get: function () {
  37124. return this._grainAnimated;
  37125. },
  37126. set: function (value) {
  37127. if (this._grainAnimated === value) {
  37128. return;
  37129. }
  37130. this._grainAnimated = value;
  37131. this._updateParameters();
  37132. },
  37133. enumerable: true,
  37134. configurable: true
  37135. });
  37136. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37137. /**
  37138. * Gets the vignette blend mode allowing different kind of effect.
  37139. */
  37140. get: function () {
  37141. return this._vignetteBlendMode;
  37142. },
  37143. /**
  37144. * Sets the vignette blend mode allowing different kind of effect.
  37145. */
  37146. set: function (value) {
  37147. if (this._vignetteBlendMode === value) {
  37148. return;
  37149. }
  37150. this._vignetteBlendMode = value;
  37151. this._updateParameters();
  37152. },
  37153. enumerable: true,
  37154. configurable: true
  37155. });
  37156. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37157. /**
  37158. * Gets wether the vignette effect is enabled.
  37159. */
  37160. get: function () {
  37161. return this._vignetteEnabled;
  37162. },
  37163. /**
  37164. * Sets wether the vignette effect is enabled.
  37165. */
  37166. set: function (value) {
  37167. if (this._vignetteEnabled === value) {
  37168. return;
  37169. }
  37170. this._vignetteEnabled = value;
  37171. this._updateParameters();
  37172. },
  37173. enumerable: true,
  37174. configurable: true
  37175. });
  37176. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37177. /**
  37178. * Gets wether the image processing is applied through a post process or not.
  37179. */
  37180. get: function () {
  37181. return this._applyByPostProcess;
  37182. },
  37183. /**
  37184. * Sets wether the image processing is applied through a post process or not.
  37185. */
  37186. set: function (value) {
  37187. if (this._applyByPostProcess === value) {
  37188. return;
  37189. }
  37190. this._applyByPostProcess = value;
  37191. this._updateParameters();
  37192. },
  37193. enumerable: true,
  37194. configurable: true
  37195. });
  37196. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37197. /**
  37198. * Gets wether the image processing is enabled or not.
  37199. */
  37200. get: function () {
  37201. return this._isEnabled;
  37202. },
  37203. /**
  37204. * Sets wether the image processing is enabled or not.
  37205. */
  37206. set: function (value) {
  37207. if (this._isEnabled === value) {
  37208. return;
  37209. }
  37210. this._isEnabled = value;
  37211. this._updateParameters();
  37212. },
  37213. enumerable: true,
  37214. configurable: true
  37215. });
  37216. /**
  37217. * Method called each time the image processing information changes requires to recompile the effect.
  37218. */
  37219. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37220. this.onUpdateParameters.notifyObservers(this);
  37221. };
  37222. ImageProcessingConfiguration.prototype.getClassName = function () {
  37223. return "ImageProcessingConfiguration";
  37224. };
  37225. /**
  37226. * Prepare the list of uniforms associated with the Image Processing effects.
  37227. * @param uniformsList The list of uniforms used in the effect
  37228. * @param defines the list of defines currently in use
  37229. */
  37230. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37231. if (defines.EXPOSURE) {
  37232. uniforms.push("exposureLinear");
  37233. }
  37234. if (defines.CONTRAST) {
  37235. uniforms.push("contrast");
  37236. }
  37237. if (defines.COLORGRADING) {
  37238. uniforms.push("colorTransformSettings");
  37239. }
  37240. if (defines.VIGNETTE) {
  37241. uniforms.push("vInverseScreenSize");
  37242. uniforms.push("vignetteSettings1");
  37243. uniforms.push("vignetteSettings2");
  37244. }
  37245. if (defines.COLORCURVES) {
  37246. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37247. }
  37248. if (defines.GRAIN) {
  37249. uniforms.push("grainVarianceAmount");
  37250. uniforms.push("grainAnimatedSeed");
  37251. }
  37252. };
  37253. /**
  37254. * Prepare the list of samplers associated with the Image Processing effects.
  37255. * @param uniformsList The list of uniforms used in the effect
  37256. * @param defines the list of defines currently in use
  37257. */
  37258. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37259. if (defines.COLORGRADING) {
  37260. samplersList.push("txColorTransform");
  37261. }
  37262. };
  37263. /**
  37264. * Prepare the list of defines associated to the shader.
  37265. * @param defines the list of defines to complete
  37266. */
  37267. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37268. if (forPostProcess === void 0) { forPostProcess = false; }
  37269. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37270. defines.VIGNETTE = false;
  37271. defines.TONEMAPPING = false;
  37272. defines.CONTRAST = false;
  37273. defines.EXPOSURE = false;
  37274. defines.COLORCURVES = false;
  37275. defines.COLORGRADING = false;
  37276. defines.COLORGRADING3D = false;
  37277. defines.IMAGEPROCESSING = false;
  37278. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37279. return;
  37280. }
  37281. defines.VIGNETTE = this.vignetteEnabled;
  37282. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37283. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37284. defines.TONEMAPPING = this.toneMappingEnabled;
  37285. defines.CONTRAST = (this.contrast !== 1.0);
  37286. defines.EXPOSURE = (this.exposure !== 1.0);
  37287. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37288. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37289. if (defines.COLORGRADING) {
  37290. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37291. }
  37292. else {
  37293. defines.COLORGRADING3D = false;
  37294. }
  37295. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37296. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37297. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37298. defines.GRAIN = this.grainEnabled;
  37299. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37300. };
  37301. /**
  37302. * Returns true if all the image processing information are ready.
  37303. */
  37304. ImageProcessingConfiguration.prototype.isReady = function () {
  37305. // Color Grading texure can not be none blocking.
  37306. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37307. };
  37308. /**
  37309. * Binds the image processing to the shader.
  37310. * @param effect The effect to bind to
  37311. */
  37312. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37313. if (aspectRatio === void 0) { aspectRatio = 1; }
  37314. // Color Curves
  37315. if (this._colorCurvesEnabled && this.colorCurves) {
  37316. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37317. }
  37318. // Vignette
  37319. if (this._vignetteEnabled) {
  37320. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37321. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37322. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37323. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37324. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37325. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37326. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37327. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37328. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37329. var vignettePower = -2.0 * this.vignetteWeight;
  37330. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37331. }
  37332. // Exposure
  37333. effect.setFloat("exposureLinear", this.exposure);
  37334. // Contrast
  37335. effect.setFloat("contrast", this.contrast);
  37336. // Color transform settings
  37337. if (this.colorGradingTexture) {
  37338. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37339. var textureSize = this.colorGradingTexture.getSize().height;
  37340. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37341. 0.5 / textureSize, // textureOffset
  37342. textureSize, // textureSize
  37343. this.colorGradingTexture.level // weight
  37344. );
  37345. }
  37346. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37347. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37348. };
  37349. /**
  37350. * Clones the current image processing instance.
  37351. * @return The cloned image processing
  37352. */
  37353. ImageProcessingConfiguration.prototype.clone = function () {
  37354. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37355. };
  37356. /**
  37357. * Serializes the current image processing instance to a json representation.
  37358. * @return a JSON representation
  37359. */
  37360. ImageProcessingConfiguration.prototype.serialize = function () {
  37361. return BABYLON.SerializationHelper.Serialize(this);
  37362. };
  37363. /**
  37364. * Parses the image processing from a json representation.
  37365. * @param source the JSON source to parse
  37366. * @return The parsed image processing
  37367. */
  37368. ImageProcessingConfiguration.Parse = function (source) {
  37369. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37370. };
  37371. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37372. /**
  37373. * Used to apply the vignette as a mix with the pixel color.
  37374. */
  37375. get: function () {
  37376. return this._VIGNETTEMODE_MULTIPLY;
  37377. },
  37378. enumerable: true,
  37379. configurable: true
  37380. });
  37381. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37382. /**
  37383. * Used to apply the vignette as a replacement of the pixel color.
  37384. */
  37385. get: function () {
  37386. return this._VIGNETTEMODE_OPAQUE;
  37387. },
  37388. enumerable: true,
  37389. configurable: true
  37390. });
  37391. // Static constants associated to the image processing.
  37392. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37393. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37394. __decorate([
  37395. BABYLON.serializeAsColorCurves()
  37396. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37397. __decorate([
  37398. BABYLON.serialize()
  37399. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37400. __decorate([
  37401. BABYLON.serializeAsTexture()
  37402. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37403. __decorate([
  37404. BABYLON.serialize()
  37405. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37406. __decorate([
  37407. BABYLON.serialize()
  37408. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37409. __decorate([
  37410. BABYLON.serialize()
  37411. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37412. __decorate([
  37413. BABYLON.serialize()
  37414. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37415. __decorate([
  37416. BABYLON.serialize()
  37417. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37418. __decorate([
  37419. BABYLON.serialize()
  37420. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37421. __decorate([
  37422. BABYLON.serialize()
  37423. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37424. __decorate([
  37425. BABYLON.serialize()
  37426. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37427. __decorate([
  37428. BABYLON.serialize()
  37429. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37430. __decorate([
  37431. BABYLON.serialize()
  37432. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37433. __decorate([
  37434. BABYLON.serializeAsColor4()
  37435. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37436. __decorate([
  37437. BABYLON.serialize()
  37438. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37439. __decorate([
  37440. BABYLON.serialize()
  37441. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37442. __decorate([
  37443. BABYLON.serialize()
  37444. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37445. __decorate([
  37446. BABYLON.serialize()
  37447. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37448. __decorate([
  37449. BABYLON.serialize()
  37450. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37451. __decorate([
  37452. BABYLON.serialize()
  37453. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37454. __decorate([
  37455. BABYLON.serialize()
  37456. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37457. __decorate([
  37458. BABYLON.serialize()
  37459. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37460. return ImageProcessingConfiguration;
  37461. }());
  37462. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37463. })(BABYLON || (BABYLON = {}));
  37464. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37465. var BABYLON;
  37466. (function (BABYLON) {
  37467. /**
  37468. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37469. * It can help converting any input color in a desired output one. This can then be used to create effects
  37470. * from sepia, black and white to sixties or futuristic rendering...
  37471. *
  37472. * The only supported format is currently 3dl.
  37473. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37474. */
  37475. var ColorGradingTexture = /** @class */ (function (_super) {
  37476. __extends(ColorGradingTexture, _super);
  37477. /**
  37478. * Instantiates a ColorGradingTexture from the following parameters.
  37479. *
  37480. * @param url The location of the color gradind data (currently only supporting 3dl)
  37481. * @param scene The scene the texture will be used in
  37482. */
  37483. function ColorGradingTexture(url, scene) {
  37484. var _this = _super.call(this, scene) || this;
  37485. if (!url) {
  37486. return _this;
  37487. }
  37488. _this._engine = scene.getEngine();
  37489. _this._textureMatrix = BABYLON.Matrix.Identity();
  37490. _this.name = url;
  37491. _this.url = url;
  37492. _this.hasAlpha = false;
  37493. _this.isCube = false;
  37494. _this.is3D = _this._engine.webGLVersion > 1;
  37495. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37496. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37497. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37498. _this.anisotropicFilteringLevel = 1;
  37499. _this._texture = _this._getFromCache(url, true);
  37500. if (!_this._texture) {
  37501. if (!scene.useDelayedTextureLoading) {
  37502. _this.loadTexture();
  37503. }
  37504. else {
  37505. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37506. }
  37507. }
  37508. return _this;
  37509. }
  37510. /**
  37511. * Returns the texture matrix used in most of the material.
  37512. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37513. */
  37514. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37515. return this._textureMatrix;
  37516. };
  37517. /**
  37518. * Occurs when the file being loaded is a .3dl LUT file.
  37519. */
  37520. ColorGradingTexture.prototype.load3dlTexture = function () {
  37521. var engine = this._engine;
  37522. var texture;
  37523. if (engine.webGLVersion === 1) {
  37524. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37525. }
  37526. else {
  37527. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37528. }
  37529. this._texture = texture;
  37530. var callback = function (text) {
  37531. if (typeof text !== "string") {
  37532. return;
  37533. }
  37534. var data = null;
  37535. var tempData = null;
  37536. var line;
  37537. var lines = text.split('\n');
  37538. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37539. var maxColor = 0;
  37540. for (var i = 0; i < lines.length; i++) {
  37541. line = lines[i];
  37542. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37543. continue;
  37544. if (line.indexOf('#') === 0)
  37545. continue;
  37546. var words = line.split(" ");
  37547. if (size === 0) {
  37548. // Number of space + one
  37549. size = words.length;
  37550. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37551. tempData = new Float32Array(size * size * size * 4);
  37552. continue;
  37553. }
  37554. if (size != 0) {
  37555. var r = Math.max(parseInt(words[0]), 0);
  37556. var g = Math.max(parseInt(words[1]), 0);
  37557. var b = Math.max(parseInt(words[2]), 0);
  37558. maxColor = Math.max(r, maxColor);
  37559. maxColor = Math.max(g, maxColor);
  37560. maxColor = Math.max(b, maxColor);
  37561. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37562. if (tempData) {
  37563. tempData[pixelStorageIndex + 0] = r;
  37564. tempData[pixelStorageIndex + 1] = g;
  37565. tempData[pixelStorageIndex + 2] = b;
  37566. }
  37567. pixelIndexSlice++;
  37568. if (pixelIndexSlice % size == 0) {
  37569. pixelIndexH++;
  37570. pixelIndexSlice = 0;
  37571. if (pixelIndexH % size == 0) {
  37572. pixelIndexW++;
  37573. pixelIndexH = 0;
  37574. }
  37575. }
  37576. }
  37577. }
  37578. if (tempData && data) {
  37579. for (var i = 0; i < tempData.length; i++) {
  37580. if (i > 0 && (i + 1) % 4 === 0) {
  37581. data[i] = 255;
  37582. }
  37583. else {
  37584. var value = tempData[i];
  37585. data[i] = (value / maxColor * 255);
  37586. }
  37587. }
  37588. }
  37589. if (texture.is3D) {
  37590. texture.updateSize(size, size, size);
  37591. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37592. }
  37593. else {
  37594. texture.updateSize(size * size, size);
  37595. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37596. }
  37597. };
  37598. var scene = this.getScene();
  37599. if (scene) {
  37600. scene._loadFile(this.url, callback);
  37601. }
  37602. else {
  37603. this._engine._loadFile(this.url, callback);
  37604. }
  37605. return this._texture;
  37606. };
  37607. /**
  37608. * Starts the loading process of the texture.
  37609. */
  37610. ColorGradingTexture.prototype.loadTexture = function () {
  37611. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37612. this.load3dlTexture();
  37613. }
  37614. };
  37615. /**
  37616. * Clones the color gradind texture.
  37617. */
  37618. ColorGradingTexture.prototype.clone = function () {
  37619. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37620. // Base texture
  37621. newTexture.level = this.level;
  37622. return newTexture;
  37623. };
  37624. /**
  37625. * Called during delayed load for textures.
  37626. */
  37627. ColorGradingTexture.prototype.delayLoad = function () {
  37628. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37629. return;
  37630. }
  37631. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37632. this._texture = this._getFromCache(this.url, true);
  37633. if (!this._texture) {
  37634. this.loadTexture();
  37635. }
  37636. };
  37637. /**
  37638. * Parses a color grading texture serialized by Babylon.
  37639. * @param parsedTexture The texture information being parsedTexture
  37640. * @param scene The scene to load the texture in
  37641. * @param rootUrl The root url of the data assets to load
  37642. * @return A color gradind texture
  37643. */
  37644. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37645. var texture = null;
  37646. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37647. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37648. texture.name = parsedTexture.name;
  37649. texture.level = parsedTexture.level;
  37650. }
  37651. return texture;
  37652. };
  37653. /**
  37654. * Serializes the LUT texture to json format.
  37655. */
  37656. ColorGradingTexture.prototype.serialize = function () {
  37657. if (!this.name) {
  37658. return null;
  37659. }
  37660. var serializationObject = {};
  37661. serializationObject.name = this.name;
  37662. serializationObject.level = this.level;
  37663. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37664. return serializationObject;
  37665. };
  37666. /**
  37667. * Empty line regex stored for GC.
  37668. */
  37669. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37670. return ColorGradingTexture;
  37671. }(BABYLON.BaseTexture));
  37672. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37673. })(BABYLON || (BABYLON = {}));
  37674. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37675. var BABYLON;
  37676. (function (BABYLON) {
  37677. /**
  37678. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37679. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37680. * 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;
  37681. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37682. */
  37683. var ColorCurves = /** @class */ (function () {
  37684. function ColorCurves() {
  37685. this._dirty = true;
  37686. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37687. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37688. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37689. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37690. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37691. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37692. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37693. this._globalHue = 30;
  37694. this._globalDensity = 0;
  37695. this._globalSaturation = 0;
  37696. this._globalExposure = 0;
  37697. this._highlightsHue = 30;
  37698. this._highlightsDensity = 0;
  37699. this._highlightsSaturation = 0;
  37700. this._highlightsExposure = 0;
  37701. this._midtonesHue = 30;
  37702. this._midtonesDensity = 0;
  37703. this._midtonesSaturation = 0;
  37704. this._midtonesExposure = 0;
  37705. this._shadowsHue = 30;
  37706. this._shadowsDensity = 0;
  37707. this._shadowsSaturation = 0;
  37708. this._shadowsExposure = 0;
  37709. }
  37710. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37711. /**
  37712. * Gets the global Hue value.
  37713. * 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).
  37714. */
  37715. get: function () {
  37716. return this._globalHue;
  37717. },
  37718. /**
  37719. * Sets the global Hue value.
  37720. * 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).
  37721. */
  37722. set: function (value) {
  37723. this._globalHue = value;
  37724. this._dirty = true;
  37725. },
  37726. enumerable: true,
  37727. configurable: true
  37728. });
  37729. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37730. /**
  37731. * Gets the global Density value.
  37732. * 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.
  37733. * Values less than zero provide a filter of opposite hue.
  37734. */
  37735. get: function () {
  37736. return this._globalDensity;
  37737. },
  37738. /**
  37739. * Sets the global Density value.
  37740. * 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.
  37741. * Values less than zero provide a filter of opposite hue.
  37742. */
  37743. set: function (value) {
  37744. this._globalDensity = value;
  37745. this._dirty = true;
  37746. },
  37747. enumerable: true,
  37748. configurable: true
  37749. });
  37750. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37751. /**
  37752. * Gets the global Saturation value.
  37753. * 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.
  37754. */
  37755. get: function () {
  37756. return this._globalSaturation;
  37757. },
  37758. /**
  37759. * Sets the global Saturation value.
  37760. * 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.
  37761. */
  37762. set: function (value) {
  37763. this._globalSaturation = value;
  37764. this._dirty = true;
  37765. },
  37766. enumerable: true,
  37767. configurable: true
  37768. });
  37769. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37770. /**
  37771. * Gets the highlights Hue value.
  37772. * 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).
  37773. */
  37774. get: function () {
  37775. return this._highlightsHue;
  37776. },
  37777. /**
  37778. * Sets the highlights Hue value.
  37779. * 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).
  37780. */
  37781. set: function (value) {
  37782. this._highlightsHue = value;
  37783. this._dirty = true;
  37784. },
  37785. enumerable: true,
  37786. configurable: true
  37787. });
  37788. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37789. /**
  37790. * Gets the highlights Density value.
  37791. * 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.
  37792. * Values less than zero provide a filter of opposite hue.
  37793. */
  37794. get: function () {
  37795. return this._highlightsDensity;
  37796. },
  37797. /**
  37798. * Sets the highlights Density value.
  37799. * 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.
  37800. * Values less than zero provide a filter of opposite hue.
  37801. */
  37802. set: function (value) {
  37803. this._highlightsDensity = value;
  37804. this._dirty = true;
  37805. },
  37806. enumerable: true,
  37807. configurable: true
  37808. });
  37809. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37810. /**
  37811. * Gets the highlights Saturation value.
  37812. * 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.
  37813. */
  37814. get: function () {
  37815. return this._highlightsSaturation;
  37816. },
  37817. /**
  37818. * Sets the highlights Saturation value.
  37819. * 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.
  37820. */
  37821. set: function (value) {
  37822. this._highlightsSaturation = value;
  37823. this._dirty = true;
  37824. },
  37825. enumerable: true,
  37826. configurable: true
  37827. });
  37828. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37829. /**
  37830. * Gets the highlights Exposure value.
  37831. * 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.
  37832. */
  37833. get: function () {
  37834. return this._highlightsExposure;
  37835. },
  37836. /**
  37837. * Sets the highlights Exposure value.
  37838. * 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.
  37839. */
  37840. set: function (value) {
  37841. this._highlightsExposure = value;
  37842. this._dirty = true;
  37843. },
  37844. enumerable: true,
  37845. configurable: true
  37846. });
  37847. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37848. /**
  37849. * Gets the midtones Hue value.
  37850. * 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).
  37851. */
  37852. get: function () {
  37853. return this._midtonesHue;
  37854. },
  37855. /**
  37856. * Sets the midtones Hue value.
  37857. * 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).
  37858. */
  37859. set: function (value) {
  37860. this._midtonesHue = value;
  37861. this._dirty = true;
  37862. },
  37863. enumerable: true,
  37864. configurable: true
  37865. });
  37866. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37867. /**
  37868. * Gets the midtones Density value.
  37869. * 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.
  37870. * Values less than zero provide a filter of opposite hue.
  37871. */
  37872. get: function () {
  37873. return this._midtonesDensity;
  37874. },
  37875. /**
  37876. * Sets the midtones Density value.
  37877. * 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.
  37878. * Values less than zero provide a filter of opposite hue.
  37879. */
  37880. set: function (value) {
  37881. this._midtonesDensity = value;
  37882. this._dirty = true;
  37883. },
  37884. enumerable: true,
  37885. configurable: true
  37886. });
  37887. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37888. /**
  37889. * Gets the midtones Saturation value.
  37890. * 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.
  37891. */
  37892. get: function () {
  37893. return this._midtonesSaturation;
  37894. },
  37895. /**
  37896. * Sets the midtones Saturation value.
  37897. * 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.
  37898. */
  37899. set: function (value) {
  37900. this._midtonesSaturation = value;
  37901. this._dirty = true;
  37902. },
  37903. enumerable: true,
  37904. configurable: true
  37905. });
  37906. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37907. /**
  37908. * Gets the midtones Exposure value.
  37909. * 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.
  37910. */
  37911. get: function () {
  37912. return this._midtonesExposure;
  37913. },
  37914. /**
  37915. * Sets the midtones Exposure value.
  37916. * 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.
  37917. */
  37918. set: function (value) {
  37919. this._midtonesExposure = value;
  37920. this._dirty = true;
  37921. },
  37922. enumerable: true,
  37923. configurable: true
  37924. });
  37925. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37926. /**
  37927. * Gets the shadows Hue value.
  37928. * 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).
  37929. */
  37930. get: function () {
  37931. return this._shadowsHue;
  37932. },
  37933. /**
  37934. * Sets the shadows Hue value.
  37935. * 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).
  37936. */
  37937. set: function (value) {
  37938. this._shadowsHue = value;
  37939. this._dirty = true;
  37940. },
  37941. enumerable: true,
  37942. configurable: true
  37943. });
  37944. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37945. /**
  37946. * Gets the shadows Density value.
  37947. * 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.
  37948. * Values less than zero provide a filter of opposite hue.
  37949. */
  37950. get: function () {
  37951. return this._shadowsDensity;
  37952. },
  37953. /**
  37954. * Sets the shadows Density value.
  37955. * 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.
  37956. * Values less than zero provide a filter of opposite hue.
  37957. */
  37958. set: function (value) {
  37959. this._shadowsDensity = value;
  37960. this._dirty = true;
  37961. },
  37962. enumerable: true,
  37963. configurable: true
  37964. });
  37965. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37966. /**
  37967. * Gets the shadows Saturation value.
  37968. * 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.
  37969. */
  37970. get: function () {
  37971. return this._shadowsSaturation;
  37972. },
  37973. /**
  37974. * Sets the shadows Saturation value.
  37975. * 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.
  37976. */
  37977. set: function (value) {
  37978. this._shadowsSaturation = value;
  37979. this._dirty = true;
  37980. },
  37981. enumerable: true,
  37982. configurable: true
  37983. });
  37984. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37985. /**
  37986. * Gets the shadows Exposure value.
  37987. * 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.
  37988. */
  37989. get: function () {
  37990. return this._shadowsExposure;
  37991. },
  37992. /**
  37993. * Sets the shadows Exposure value.
  37994. * 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.
  37995. */
  37996. set: function (value) {
  37997. this._shadowsExposure = value;
  37998. this._dirty = true;
  37999. },
  38000. enumerable: true,
  38001. configurable: true
  38002. });
  38003. ColorCurves.prototype.getClassName = function () {
  38004. return "ColorCurves";
  38005. };
  38006. /**
  38007. * Binds the color curves to the shader.
  38008. * @param colorCurves The color curve to bind
  38009. * @param effect The effect to bind to
  38010. */
  38011. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38012. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38013. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38014. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38015. if (colorCurves._dirty) {
  38016. colorCurves._dirty = false;
  38017. // Fill in global info.
  38018. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38019. // Compute highlights info.
  38020. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38021. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38022. // Compute midtones info.
  38023. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38024. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38025. // Compute shadows info.
  38026. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38027. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38028. // Compute deltas (neutral is midtones).
  38029. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38030. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38031. }
  38032. if (effect) {
  38033. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38034. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38035. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38036. }
  38037. };
  38038. /**
  38039. * Prepare the list of uniforms associated with the ColorCurves effects.
  38040. * @param uniformsList The list of uniforms used in the effect
  38041. */
  38042. ColorCurves.PrepareUniforms = function (uniformsList) {
  38043. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38044. };
  38045. /**
  38046. * Returns color grading data based on a hue, density, saturation and exposure value.
  38047. * @param filterHue The hue of the color filter.
  38048. * @param filterDensity The density of the color filter.
  38049. * @param saturation The saturation.
  38050. * @param exposure The exposure.
  38051. * @param result The result data container.
  38052. */
  38053. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38054. if (hue == null) {
  38055. return;
  38056. }
  38057. hue = ColorCurves.clamp(hue, 0, 360);
  38058. density = ColorCurves.clamp(density, -100, 100);
  38059. saturation = ColorCurves.clamp(saturation, -100, 100);
  38060. exposure = ColorCurves.clamp(exposure, -100, 100);
  38061. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38062. // so that the maximum filter density is only 50% control. This provides fine control
  38063. // for small values and reasonable range.
  38064. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38065. density *= 0.5;
  38066. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38067. if (density < 0) {
  38068. density *= -1;
  38069. hue = (hue + 180) % 360;
  38070. }
  38071. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38072. result.scaleToRef(2, result);
  38073. result.a = 1 + 0.01 * saturation;
  38074. };
  38075. /**
  38076. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38077. * @param value The input slider value in range [-100,100].
  38078. * @returns Adjusted value.
  38079. */
  38080. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38081. value /= 100;
  38082. var x = Math.abs(value);
  38083. x = Math.pow(x, 2);
  38084. if (value < 0) {
  38085. x *= -1;
  38086. }
  38087. x *= 100;
  38088. return x;
  38089. };
  38090. /**
  38091. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38092. * @param hue The hue (H) input.
  38093. * @param saturation The saturation (S) input.
  38094. * @param brightness The brightness (B) input.
  38095. * @result An RGBA color represented as Vector4.
  38096. */
  38097. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38098. var h = ColorCurves.clamp(hue, 0, 360);
  38099. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38100. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38101. if (s === 0) {
  38102. result.r = v;
  38103. result.g = v;
  38104. result.b = v;
  38105. }
  38106. else {
  38107. // sector 0 to 5
  38108. h /= 60;
  38109. var i = Math.floor(h);
  38110. // fractional part of h
  38111. var f = h - i;
  38112. var p = v * (1 - s);
  38113. var q = v * (1 - s * f);
  38114. var t = v * (1 - s * (1 - f));
  38115. switch (i) {
  38116. case 0:
  38117. result.r = v;
  38118. result.g = t;
  38119. result.b = p;
  38120. break;
  38121. case 1:
  38122. result.r = q;
  38123. result.g = v;
  38124. result.b = p;
  38125. break;
  38126. case 2:
  38127. result.r = p;
  38128. result.g = v;
  38129. result.b = t;
  38130. break;
  38131. case 3:
  38132. result.r = p;
  38133. result.g = q;
  38134. result.b = v;
  38135. break;
  38136. case 4:
  38137. result.r = t;
  38138. result.g = p;
  38139. result.b = v;
  38140. break;
  38141. default:// case 5:
  38142. result.r = v;
  38143. result.g = p;
  38144. result.b = q;
  38145. break;
  38146. }
  38147. }
  38148. result.a = 1;
  38149. };
  38150. /**
  38151. * Returns a value clamped between min and max
  38152. * @param value The value to clamp
  38153. * @param min The minimum of value
  38154. * @param max The maximum of value
  38155. * @returns The clamped value.
  38156. */
  38157. ColorCurves.clamp = function (value, min, max) {
  38158. return Math.min(Math.max(value, min), max);
  38159. };
  38160. /**
  38161. * Clones the current color curve instance.
  38162. * @return The cloned curves
  38163. */
  38164. ColorCurves.prototype.clone = function () {
  38165. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38166. };
  38167. /**
  38168. * Serializes the current color curve instance to a json representation.
  38169. * @return a JSON representation
  38170. */
  38171. ColorCurves.prototype.serialize = function () {
  38172. return BABYLON.SerializationHelper.Serialize(this);
  38173. };
  38174. /**
  38175. * Parses the color curve from a json representation.
  38176. * @param source the JSON source to parse
  38177. * @return The parsed curves
  38178. */
  38179. ColorCurves.Parse = function (source) {
  38180. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38181. };
  38182. __decorate([
  38183. BABYLON.serialize()
  38184. ], ColorCurves.prototype, "_globalHue", void 0);
  38185. __decorate([
  38186. BABYLON.serialize()
  38187. ], ColorCurves.prototype, "_globalDensity", void 0);
  38188. __decorate([
  38189. BABYLON.serialize()
  38190. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38191. __decorate([
  38192. BABYLON.serialize()
  38193. ], ColorCurves.prototype, "_globalExposure", void 0);
  38194. __decorate([
  38195. BABYLON.serialize()
  38196. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38197. __decorate([
  38198. BABYLON.serialize()
  38199. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38200. __decorate([
  38201. BABYLON.serialize()
  38202. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38203. __decorate([
  38204. BABYLON.serialize()
  38205. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38206. __decorate([
  38207. BABYLON.serialize()
  38208. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38209. __decorate([
  38210. BABYLON.serialize()
  38211. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38212. __decorate([
  38213. BABYLON.serialize()
  38214. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38215. __decorate([
  38216. BABYLON.serialize()
  38217. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38218. return ColorCurves;
  38219. }());
  38220. BABYLON.ColorCurves = ColorCurves;
  38221. })(BABYLON || (BABYLON = {}));
  38222. //# sourceMappingURL=babylon.colorCurves.js.map
  38223. //# sourceMappingURL=babylon.behavior.js.map
  38224. var BABYLON;
  38225. (function (BABYLON) {
  38226. /**
  38227. * "Static Class" containing the most commonly used helper while dealing with material for
  38228. * rendering purpose.
  38229. *
  38230. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38231. *
  38232. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38233. */
  38234. var MaterialHelper = /** @class */ (function () {
  38235. function MaterialHelper() {
  38236. }
  38237. /**
  38238. * Bind the current view position to an effect.
  38239. * @param effect The effect to be bound
  38240. * @param scene The scene the eyes position is used from
  38241. */
  38242. MaterialHelper.BindEyePosition = function (effect, scene) {
  38243. if (scene._forcedViewPosition) {
  38244. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38245. return;
  38246. }
  38247. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38248. };
  38249. /**
  38250. * Helps preparing the defines values about the UVs in used in the effect.
  38251. * UVs are shared as much as we can accross chanels in the shaders.
  38252. * @param texture The texture we are preparing the UVs for
  38253. * @param defines The defines to update
  38254. * @param key The chanel key "diffuse", "specular"... used in the shader
  38255. */
  38256. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38257. defines._needUVs = true;
  38258. defines[key] = true;
  38259. if (texture.getTextureMatrix().isIdentity(true)) {
  38260. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38261. if (texture.coordinatesIndex === 0) {
  38262. defines["MAINUV1"] = true;
  38263. }
  38264. else {
  38265. defines["MAINUV2"] = true;
  38266. }
  38267. }
  38268. else {
  38269. defines[key + "DIRECTUV"] = 0;
  38270. }
  38271. };
  38272. /**
  38273. * Binds a texture matrix value to its corrsponding uniform
  38274. * @param texture The texture to bind the matrix for
  38275. * @param uniformBuffer The uniform buffer receivin the data
  38276. * @param key The chanel key "diffuse", "specular"... used in the shader
  38277. */
  38278. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38279. var matrix = texture.getTextureMatrix();
  38280. if (!matrix.isIdentity(true)) {
  38281. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38282. }
  38283. };
  38284. /**
  38285. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38286. * @param mesh defines the current mesh
  38287. * @param scene defines the current scene
  38288. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38289. * @param pointsCloud defines if point cloud rendering has to be turned on
  38290. * @param fogEnabled defines if fog has to be turned on
  38291. * @param alphaTest defines if alpha testing has to be turned on
  38292. * @param defines defines the current list of defines
  38293. */
  38294. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38295. if (defines._areMiscDirty) {
  38296. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38297. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38298. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38299. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38300. defines["ALPHATEST"] = alphaTest;
  38301. }
  38302. };
  38303. /**
  38304. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38305. * @param scene defines the current scene
  38306. * @param engine defines the current engine
  38307. * @param defines specifies the list of active defines
  38308. * @param useInstances defines if instances have to be turned on
  38309. * @param useClipPlane defines if clip plane have to be turned on
  38310. */
  38311. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38312. if (useClipPlane === void 0) { useClipPlane = null; }
  38313. var changed = false;
  38314. if (useClipPlane == null) {
  38315. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38316. }
  38317. if (defines["CLIPPLANE"] !== useClipPlane) {
  38318. defines["CLIPPLANE"] = useClipPlane;
  38319. changed = true;
  38320. }
  38321. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38322. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38323. changed = true;
  38324. }
  38325. if (defines["INSTANCES"] !== useInstances) {
  38326. defines["INSTANCES"] = useInstances;
  38327. changed = true;
  38328. }
  38329. if (changed) {
  38330. defines.markAsUnprocessed();
  38331. }
  38332. };
  38333. /**
  38334. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38335. * @param mesh The mesh containing the geometry data we will draw
  38336. * @param defines The defines to update
  38337. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38338. * @param useBones Precise whether bones should be used or not (override mesh info)
  38339. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38340. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38341. * @returns false if defines are considered not dirty and have not been checked
  38342. */
  38343. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38344. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38345. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38346. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38347. return false;
  38348. }
  38349. defines._normals = defines._needNormals;
  38350. defines._uvs = defines._needUVs;
  38351. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38352. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38353. defines["TANGENT"] = true;
  38354. }
  38355. if (defines._needUVs) {
  38356. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38357. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38358. }
  38359. else {
  38360. defines["UV1"] = false;
  38361. defines["UV2"] = false;
  38362. }
  38363. if (useVertexColor) {
  38364. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38365. defines["VERTEXCOLOR"] = hasVertexColors;
  38366. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38367. }
  38368. if (useBones) {
  38369. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38370. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38371. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38372. }
  38373. else {
  38374. defines["NUM_BONE_INFLUENCERS"] = 0;
  38375. defines["BonesPerMesh"] = 0;
  38376. }
  38377. }
  38378. if (useMorphTargets) {
  38379. var manager = mesh.morphTargetManager;
  38380. if (manager) {
  38381. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38382. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38383. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38384. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38385. }
  38386. else {
  38387. defines["MORPHTARGETS_TANGENT"] = false;
  38388. defines["MORPHTARGETS_NORMAL"] = false;
  38389. defines["MORPHTARGETS"] = false;
  38390. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38391. }
  38392. }
  38393. return true;
  38394. };
  38395. /**
  38396. * Prepares the defines related to the light information passed in parameter
  38397. * @param scene The scene we are intending to draw
  38398. * @param mesh The mesh the effect is compiling for
  38399. * @param defines The defines to update
  38400. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38401. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38402. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38403. * @returns true if normals will be required for the rest of the effect
  38404. */
  38405. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38406. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38407. if (disableLighting === void 0) { disableLighting = false; }
  38408. if (!defines._areLightsDirty) {
  38409. return defines._needNormals;
  38410. }
  38411. var lightIndex = 0;
  38412. var needNormals = false;
  38413. var needRebuild = false;
  38414. var lightmapMode = false;
  38415. var shadowEnabled = false;
  38416. var specularEnabled = false;
  38417. if (scene.lightsEnabled && !disableLighting) {
  38418. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38419. var light = _a[_i];
  38420. needNormals = true;
  38421. if (defines["LIGHT" + lightIndex] === undefined) {
  38422. needRebuild = true;
  38423. }
  38424. defines["LIGHT" + lightIndex] = true;
  38425. defines["SPOTLIGHT" + lightIndex] = false;
  38426. defines["HEMILIGHT" + lightIndex] = false;
  38427. defines["POINTLIGHT" + lightIndex] = false;
  38428. defines["DIRLIGHT" + lightIndex] = false;
  38429. var type;
  38430. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38431. type = "SPOTLIGHT" + lightIndex;
  38432. var spotLight = light;
  38433. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38434. }
  38435. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38436. type = "HEMILIGHT" + lightIndex;
  38437. }
  38438. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38439. type = "POINTLIGHT" + lightIndex;
  38440. }
  38441. else {
  38442. type = "DIRLIGHT" + lightIndex;
  38443. }
  38444. defines[type] = true;
  38445. // Specular
  38446. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38447. specularEnabled = true;
  38448. }
  38449. // Shadows
  38450. defines["SHADOW" + lightIndex] = false;
  38451. defines["SHADOWPCF" + lightIndex] = false;
  38452. defines["SHADOWESM" + lightIndex] = false;
  38453. defines["SHADOWCUBE" + lightIndex] = false;
  38454. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38455. var shadowGenerator = light.getShadowGenerator();
  38456. if (shadowGenerator) {
  38457. shadowEnabled = true;
  38458. shadowGenerator.prepareDefines(defines, lightIndex);
  38459. }
  38460. }
  38461. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38462. lightmapMode = true;
  38463. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38464. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38465. }
  38466. else {
  38467. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38468. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38469. }
  38470. lightIndex++;
  38471. if (lightIndex === maxSimultaneousLights)
  38472. break;
  38473. }
  38474. }
  38475. defines["SPECULARTERM"] = specularEnabled;
  38476. defines["SHADOWS"] = shadowEnabled;
  38477. // Resetting all other lights if any
  38478. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38479. if (defines["LIGHT" + index] !== undefined) {
  38480. defines["LIGHT" + index] = false;
  38481. defines["HEMILIGHT" + lightIndex] = false;
  38482. defines["POINTLIGHT" + lightIndex] = false;
  38483. defines["DIRLIGHT" + lightIndex] = false;
  38484. defines["SPOTLIGHT" + lightIndex] = false;
  38485. defines["SHADOW" + lightIndex] = false;
  38486. }
  38487. }
  38488. var caps = scene.getEngine().getCaps();
  38489. if (defines["SHADOWFLOAT"] === undefined) {
  38490. needRebuild = true;
  38491. }
  38492. defines["SHADOWFLOAT"] = shadowEnabled &&
  38493. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38494. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38495. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38496. if (needRebuild) {
  38497. defines.rebuild();
  38498. }
  38499. return needNormals;
  38500. };
  38501. /**
  38502. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38503. * that won t be acctive due to defines being turned off.
  38504. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38505. * @param samplersList The samplers list
  38506. * @param defines The defines helping in the list generation
  38507. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38508. */
  38509. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38510. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38511. var uniformsList;
  38512. var uniformBuffersList = null;
  38513. if (uniformsListOrOptions.uniformsNames) {
  38514. var options = uniformsListOrOptions;
  38515. uniformsList = options.uniformsNames;
  38516. uniformBuffersList = options.uniformBuffersNames;
  38517. samplersList = options.samplers;
  38518. defines = options.defines;
  38519. maxSimultaneousLights = options.maxSimultaneousLights;
  38520. }
  38521. else {
  38522. uniformsList = uniformsListOrOptions;
  38523. if (!samplersList) {
  38524. samplersList = [];
  38525. }
  38526. }
  38527. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38528. if (!defines["LIGHT" + lightIndex]) {
  38529. break;
  38530. }
  38531. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38532. if (uniformBuffersList) {
  38533. uniformBuffersList.push("Light" + lightIndex);
  38534. }
  38535. samplersList.push("shadowSampler" + lightIndex);
  38536. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38537. samplersList.push("projectionLightSampler" + lightIndex);
  38538. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38539. }
  38540. }
  38541. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38542. uniformsList.push("morphTargetInfluences");
  38543. }
  38544. };
  38545. /**
  38546. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38547. * @param defines The defines to update while falling back
  38548. * @param fallbacks The authorized effect fallbacks
  38549. * @param maxSimultaneousLights The maximum number of lights allowed
  38550. * @param rank the current rank of the Effect
  38551. * @returns The newly affected rank
  38552. */
  38553. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38554. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38555. if (rank === void 0) { rank = 0; }
  38556. var lightFallbackRank = 0;
  38557. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38558. if (!defines["LIGHT" + lightIndex]) {
  38559. break;
  38560. }
  38561. if (lightIndex > 0) {
  38562. lightFallbackRank = rank + lightIndex;
  38563. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38564. }
  38565. if (!defines["SHADOWS"]) {
  38566. if (defines["SHADOW" + lightIndex]) {
  38567. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38568. }
  38569. if (defines["SHADOWPCF" + lightIndex]) {
  38570. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38571. }
  38572. if (defines["SHADOWESM" + lightIndex]) {
  38573. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38574. }
  38575. }
  38576. }
  38577. return lightFallbackRank++;
  38578. };
  38579. /**
  38580. * Prepares the list of attributes required for morph targets according to the effect defines.
  38581. * @param attribs The current list of supported attribs
  38582. * @param mesh The mesh to prepare the morph targets attributes for
  38583. * @param defines The current Defines of the effect
  38584. */
  38585. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38586. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38587. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38588. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38589. var manager = mesh.morphTargetManager;
  38590. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38591. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38592. for (var index = 0; index < influencers; index++) {
  38593. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38594. if (normal) {
  38595. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38596. }
  38597. if (tangent) {
  38598. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38599. }
  38600. if (attribs.length > maxAttributesCount) {
  38601. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38602. }
  38603. }
  38604. }
  38605. };
  38606. /**
  38607. * Prepares the list of attributes required for bones according to the effect defines.
  38608. * @param attribs The current list of supported attribs
  38609. * @param mesh The mesh to prepare the bones attributes for
  38610. * @param defines The current Defines of the effect
  38611. * @param fallbacks The current efffect fallback strategy
  38612. */
  38613. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38614. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38615. fallbacks.addCPUSkinningFallback(0, mesh);
  38616. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38617. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38618. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38619. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38620. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38621. }
  38622. }
  38623. };
  38624. /**
  38625. * Prepares the list of attributes required for instances according to the effect defines.
  38626. * @param attribs The current list of supported attribs
  38627. * @param defines The current Defines of the effect
  38628. */
  38629. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38630. if (defines["INSTANCES"]) {
  38631. attribs.push("world0");
  38632. attribs.push("world1");
  38633. attribs.push("world2");
  38634. attribs.push("world3");
  38635. }
  38636. };
  38637. /**
  38638. * Binds the light shadow information to the effect for the given mesh.
  38639. * @param light The light containing the generator
  38640. * @param scene The scene the lights belongs to
  38641. * @param mesh The mesh we are binding the information to render
  38642. * @param lightIndex The light index in the effect used to render the mesh
  38643. * @param effect The effect we are binding the data to
  38644. */
  38645. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38646. if (light.shadowEnabled && mesh.receiveShadows) {
  38647. var shadowGenerator = light.getShadowGenerator();
  38648. if (shadowGenerator) {
  38649. shadowGenerator.bindShadowLight(lightIndex, effect);
  38650. }
  38651. }
  38652. };
  38653. /**
  38654. * Binds the light information to the effect.
  38655. * @param light The light containing the generator
  38656. * @param effect The effect we are binding the data to
  38657. * @param lightIndex The light index in the effect used to render
  38658. */
  38659. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38660. light.transferToEffect(effect, lightIndex + "");
  38661. };
  38662. /**
  38663. * Binds the lights information from the scene to the effect for the given mesh.
  38664. * @param scene The scene the lights belongs to
  38665. * @param mesh The mesh we are binding the information to render
  38666. * @param effect The effect we are binding the data to
  38667. * @param defines The generated defines for the effect
  38668. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38669. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38670. */
  38671. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38672. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38673. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38674. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38675. for (var i = 0; i < len; i++) {
  38676. var light = mesh._lightSources[i];
  38677. var iAsString = i.toString();
  38678. var scaledIntensity = light.getScaledIntensity();
  38679. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38680. MaterialHelper.BindLightProperties(light, effect, i);
  38681. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38682. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38683. if (defines["SPECULARTERM"]) {
  38684. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38685. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38686. }
  38687. // Shadows
  38688. if (scene.shadowsEnabled) {
  38689. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38690. }
  38691. light._uniformBuffer.update();
  38692. }
  38693. };
  38694. /**
  38695. * Binds the fog information from the scene to the effect for the given mesh.
  38696. * @param scene The scene the lights belongs to
  38697. * @param mesh The mesh we are binding the information to render
  38698. * @param effect The effect we are binding the data to
  38699. */
  38700. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38701. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38702. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38703. effect.setColor3("vFogColor", scene.fogColor);
  38704. }
  38705. };
  38706. /**
  38707. * Binds the bones information from the mesh to the effect.
  38708. * @param mesh The mesh we are binding the information to render
  38709. * @param effect The effect we are binding the data to
  38710. */
  38711. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38712. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38713. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38714. if (matrices && effect) {
  38715. effect.setMatrices("mBones", matrices);
  38716. }
  38717. }
  38718. };
  38719. /**
  38720. * Binds the morph targets information from the mesh to the effect.
  38721. * @param abstractMesh The mesh we are binding the information to render
  38722. * @param effect The effect we are binding the data to
  38723. */
  38724. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38725. var manager = abstractMesh.morphTargetManager;
  38726. if (!abstractMesh || !manager) {
  38727. return;
  38728. }
  38729. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38730. };
  38731. /**
  38732. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38733. * @param defines The generated defines used in the effect
  38734. * @param effect The effect we are binding the data to
  38735. * @param scene The scene we are willing to render with logarithmic scale for
  38736. */
  38737. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38738. if (defines["LOGARITHMICDEPTH"]) {
  38739. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38740. }
  38741. };
  38742. /**
  38743. * Binds the clip plane information from the scene to the effect.
  38744. * @param scene The scene the clip plane information are extracted from
  38745. * @param effect The effect we are binding the data to
  38746. */
  38747. MaterialHelper.BindClipPlane = function (effect, scene) {
  38748. if (scene.clipPlane) {
  38749. var clipPlane = scene.clipPlane;
  38750. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38751. }
  38752. };
  38753. return MaterialHelper;
  38754. }());
  38755. BABYLON.MaterialHelper = MaterialHelper;
  38756. })(BABYLON || (BABYLON = {}));
  38757. //# sourceMappingURL=babylon.materialHelper.js.map
  38758. var BABYLON;
  38759. (function (BABYLON) {
  38760. var PushMaterial = /** @class */ (function (_super) {
  38761. __extends(PushMaterial, _super);
  38762. function PushMaterial(name, scene) {
  38763. var _this = _super.call(this, name, scene) || this;
  38764. _this._normalMatrix = new BABYLON.Matrix();
  38765. _this.storeEffectOnSubMeshes = true;
  38766. return _this;
  38767. }
  38768. PushMaterial.prototype.getEffect = function () {
  38769. return this._activeEffect;
  38770. };
  38771. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38772. if (!mesh) {
  38773. return false;
  38774. }
  38775. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38776. return true;
  38777. }
  38778. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38779. };
  38780. /**
  38781. * Binds the given world matrix to the active effect
  38782. *
  38783. * @param world the matrix to bind
  38784. */
  38785. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38786. this._activeEffect.setMatrix("world", world);
  38787. };
  38788. /**
  38789. * Binds the given normal matrix to the active effect
  38790. *
  38791. * @param normalMatrix the matrix to bind
  38792. */
  38793. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38794. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38795. };
  38796. PushMaterial.prototype.bind = function (world, mesh) {
  38797. if (!mesh) {
  38798. return;
  38799. }
  38800. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38801. };
  38802. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38803. if (effect === void 0) { effect = null; }
  38804. _super.prototype._afterBind.call(this, mesh);
  38805. this.getScene()._cachedEffect = effect;
  38806. };
  38807. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38808. if (visibility === void 0) { visibility = 1; }
  38809. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38810. };
  38811. return PushMaterial;
  38812. }(BABYLON.Material));
  38813. BABYLON.PushMaterial = PushMaterial;
  38814. })(BABYLON || (BABYLON = {}));
  38815. //# sourceMappingURL=babylon.pushMaterial.js.map
  38816. var BABYLON;
  38817. (function (BABYLON) {
  38818. /** @ignore */
  38819. var StandardMaterialDefines = /** @class */ (function (_super) {
  38820. __extends(StandardMaterialDefines, _super);
  38821. function StandardMaterialDefines() {
  38822. var _this = _super.call(this) || this;
  38823. _this.MAINUV1 = false;
  38824. _this.MAINUV2 = false;
  38825. _this.DIFFUSE = false;
  38826. _this.DIFFUSEDIRECTUV = 0;
  38827. _this.AMBIENT = false;
  38828. _this.AMBIENTDIRECTUV = 0;
  38829. _this.OPACITY = false;
  38830. _this.OPACITYDIRECTUV = 0;
  38831. _this.OPACITYRGB = false;
  38832. _this.REFLECTION = false;
  38833. _this.EMISSIVE = false;
  38834. _this.EMISSIVEDIRECTUV = 0;
  38835. _this.SPECULAR = false;
  38836. _this.SPECULARDIRECTUV = 0;
  38837. _this.BUMP = false;
  38838. _this.BUMPDIRECTUV = 0;
  38839. _this.PARALLAX = false;
  38840. _this.PARALLAXOCCLUSION = false;
  38841. _this.SPECULAROVERALPHA = false;
  38842. _this.CLIPPLANE = false;
  38843. _this.ALPHATEST = false;
  38844. _this.DEPTHPREPASS = false;
  38845. _this.ALPHAFROMDIFFUSE = false;
  38846. _this.POINTSIZE = false;
  38847. _this.FOG = false;
  38848. _this.SPECULARTERM = false;
  38849. _this.DIFFUSEFRESNEL = false;
  38850. _this.OPACITYFRESNEL = false;
  38851. _this.REFLECTIONFRESNEL = false;
  38852. _this.REFRACTIONFRESNEL = false;
  38853. _this.EMISSIVEFRESNEL = false;
  38854. _this.FRESNEL = false;
  38855. _this.NORMAL = false;
  38856. _this.UV1 = false;
  38857. _this.UV2 = false;
  38858. _this.VERTEXCOLOR = false;
  38859. _this.VERTEXALPHA = false;
  38860. _this.NUM_BONE_INFLUENCERS = 0;
  38861. _this.BonesPerMesh = 0;
  38862. _this.INSTANCES = false;
  38863. _this.GLOSSINESS = false;
  38864. _this.ROUGHNESS = false;
  38865. _this.EMISSIVEASILLUMINATION = false;
  38866. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38867. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38868. _this.LIGHTMAP = false;
  38869. _this.LIGHTMAPDIRECTUV = 0;
  38870. _this.OBJECTSPACE_NORMALMAP = false;
  38871. _this.USELIGHTMAPASSHADOWMAP = false;
  38872. _this.REFLECTIONMAP_3D = false;
  38873. _this.REFLECTIONMAP_SPHERICAL = false;
  38874. _this.REFLECTIONMAP_PLANAR = false;
  38875. _this.REFLECTIONMAP_CUBIC = false;
  38876. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38877. _this.REFLECTIONMAP_PROJECTION = false;
  38878. _this.REFLECTIONMAP_SKYBOX = false;
  38879. _this.REFLECTIONMAP_EXPLICIT = false;
  38880. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38881. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38882. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38883. _this.INVERTCUBICMAP = false;
  38884. _this.LOGARITHMICDEPTH = false;
  38885. _this.REFRACTION = false;
  38886. _this.REFRACTIONMAP_3D = false;
  38887. _this.REFLECTIONOVERALPHA = false;
  38888. _this.TWOSIDEDLIGHTING = false;
  38889. _this.SHADOWFLOAT = false;
  38890. _this.MORPHTARGETS = false;
  38891. _this.MORPHTARGETS_NORMAL = false;
  38892. _this.MORPHTARGETS_TANGENT = false;
  38893. _this.NUM_MORPH_INFLUENCERS = 0;
  38894. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38895. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38896. _this.IMAGEPROCESSING = false;
  38897. _this.VIGNETTE = false;
  38898. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38899. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38900. _this.TONEMAPPING = false;
  38901. _this.CONTRAST = false;
  38902. _this.COLORCURVES = false;
  38903. _this.COLORGRADING = false;
  38904. _this.COLORGRADING3D = false;
  38905. _this.SAMPLER3DGREENDEPTH = false;
  38906. _this.SAMPLER3DBGRMAP = false;
  38907. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38908. _this.EXPOSURE = false;
  38909. _this.GRAIN = false;
  38910. _this.rebuild();
  38911. return _this;
  38912. }
  38913. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38914. var modes = [
  38915. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38916. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38917. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38918. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38919. ];
  38920. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38921. var mode = modes_1[_i];
  38922. this[mode] = (mode === modeToEnable);
  38923. }
  38924. };
  38925. return StandardMaterialDefines;
  38926. }(BABYLON.MaterialDefines));
  38927. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38928. var StandardMaterial = /** @class */ (function (_super) {
  38929. __extends(StandardMaterial, _super);
  38930. function StandardMaterial(name, scene) {
  38931. var _this = _super.call(this, name, scene) || this;
  38932. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38933. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38934. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38935. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38936. _this.specularPower = 64;
  38937. _this._useAlphaFromDiffuseTexture = false;
  38938. _this._useEmissiveAsIllumination = false;
  38939. _this._linkEmissiveWithDiffuse = false;
  38940. _this._useSpecularOverAlpha = false;
  38941. _this._useReflectionOverAlpha = false;
  38942. _this._disableLighting = false;
  38943. _this._useObjectSpaceNormalMap = false;
  38944. _this._useParallax = false;
  38945. _this._useParallaxOcclusion = false;
  38946. _this.parallaxScaleBias = 0.05;
  38947. _this._roughness = 0;
  38948. _this.indexOfRefraction = 0.98;
  38949. _this.invertRefractionY = true;
  38950. _this._useLightmapAsShadowmap = false;
  38951. _this._useReflectionFresnelFromSpecular = false;
  38952. _this._useGlossinessFromSpecularMapAlpha = false;
  38953. _this._maxSimultaneousLights = 4;
  38954. /**
  38955. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38956. */
  38957. _this._invertNormalMapX = false;
  38958. /**
  38959. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38960. */
  38961. _this._invertNormalMapY = false;
  38962. /**
  38963. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38964. */
  38965. _this._twoSidedLighting = false;
  38966. _this._renderTargets = new BABYLON.SmartArray(16);
  38967. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38968. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38969. // Setup the default processing configuration to the scene.
  38970. _this._attachImageProcessingConfiguration(null);
  38971. _this.getRenderTargetTextures = function () {
  38972. _this._renderTargets.reset();
  38973. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38974. _this._renderTargets.push(_this._reflectionTexture);
  38975. }
  38976. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38977. _this._renderTargets.push(_this._refractionTexture);
  38978. }
  38979. return _this._renderTargets;
  38980. };
  38981. return _this;
  38982. }
  38983. ;
  38984. ;
  38985. ;
  38986. ;
  38987. ;
  38988. ;
  38989. ;
  38990. ;
  38991. ;
  38992. ;
  38993. ;
  38994. ;
  38995. ;
  38996. ;
  38997. ;
  38998. ;
  38999. ;
  39000. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39001. /**
  39002. * Gets the image processing configuration used either in this material.
  39003. */
  39004. get: function () {
  39005. return this._imageProcessingConfiguration;
  39006. },
  39007. /**
  39008. * Sets the Default image processing configuration used either in the this material.
  39009. *
  39010. * If sets to null, the scene one is in use.
  39011. */
  39012. set: function (value) {
  39013. this._attachImageProcessingConfiguration(value);
  39014. // Ensure the effect will be rebuilt.
  39015. this._markAllSubMeshesAsTexturesDirty();
  39016. },
  39017. enumerable: true,
  39018. configurable: true
  39019. });
  39020. /**
  39021. * Attaches a new image processing configuration to the Standard Material.
  39022. * @param configuration
  39023. */
  39024. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39025. var _this = this;
  39026. if (configuration === this._imageProcessingConfiguration) {
  39027. return;
  39028. }
  39029. // Detaches observer.
  39030. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39031. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39032. }
  39033. // Pick the scene configuration if needed.
  39034. if (!configuration) {
  39035. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39036. }
  39037. else {
  39038. this._imageProcessingConfiguration = configuration;
  39039. }
  39040. // Attaches observer.
  39041. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39042. _this._markAllSubMeshesAsImageProcessingDirty();
  39043. });
  39044. };
  39045. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39046. /**
  39047. * Gets wether the color curves effect is enabled.
  39048. */
  39049. get: function () {
  39050. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39051. },
  39052. /**
  39053. * Sets wether the color curves effect is enabled.
  39054. */
  39055. set: function (value) {
  39056. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39057. },
  39058. enumerable: true,
  39059. configurable: true
  39060. });
  39061. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39062. /**
  39063. * Gets wether the color grading effect is enabled.
  39064. */
  39065. get: function () {
  39066. return this.imageProcessingConfiguration.colorGradingEnabled;
  39067. },
  39068. /**
  39069. * Gets wether the color grading effect is enabled.
  39070. */
  39071. set: function (value) {
  39072. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39073. },
  39074. enumerable: true,
  39075. configurable: true
  39076. });
  39077. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39078. /**
  39079. * Gets wether tonemapping is enabled or not.
  39080. */
  39081. get: function () {
  39082. return this._imageProcessingConfiguration.toneMappingEnabled;
  39083. },
  39084. /**
  39085. * Sets wether tonemapping is enabled or not
  39086. */
  39087. set: function (value) {
  39088. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39089. },
  39090. enumerable: true,
  39091. configurable: true
  39092. });
  39093. ;
  39094. ;
  39095. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39096. /**
  39097. * The camera exposure used on this material.
  39098. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39099. * This corresponds to a photographic exposure.
  39100. */
  39101. get: function () {
  39102. return this._imageProcessingConfiguration.exposure;
  39103. },
  39104. /**
  39105. * The camera exposure used on this material.
  39106. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39107. * This corresponds to a photographic exposure.
  39108. */
  39109. set: function (value) {
  39110. this._imageProcessingConfiguration.exposure = value;
  39111. },
  39112. enumerable: true,
  39113. configurable: true
  39114. });
  39115. ;
  39116. ;
  39117. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39118. /**
  39119. * Gets The camera contrast used on this material.
  39120. */
  39121. get: function () {
  39122. return this._imageProcessingConfiguration.contrast;
  39123. },
  39124. /**
  39125. * Sets The camera contrast used on this material.
  39126. */
  39127. set: function (value) {
  39128. this._imageProcessingConfiguration.contrast = value;
  39129. },
  39130. enumerable: true,
  39131. configurable: true
  39132. });
  39133. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39134. /**
  39135. * Gets the Color Grading 2D Lookup Texture.
  39136. */
  39137. get: function () {
  39138. return this._imageProcessingConfiguration.colorGradingTexture;
  39139. },
  39140. /**
  39141. * Sets the Color Grading 2D Lookup Texture.
  39142. */
  39143. set: function (value) {
  39144. this._imageProcessingConfiguration.colorGradingTexture = value;
  39145. },
  39146. enumerable: true,
  39147. configurable: true
  39148. });
  39149. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39150. /**
  39151. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39152. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39153. * 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;
  39154. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39155. */
  39156. get: function () {
  39157. return this._imageProcessingConfiguration.colorCurves;
  39158. },
  39159. /**
  39160. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39161. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39162. * 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;
  39163. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39164. */
  39165. set: function (value) {
  39166. this._imageProcessingConfiguration.colorCurves = value;
  39167. },
  39168. enumerable: true,
  39169. configurable: true
  39170. });
  39171. StandardMaterial.prototype.getClassName = function () {
  39172. return "StandardMaterial";
  39173. };
  39174. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39175. get: function () {
  39176. return this._useLogarithmicDepth;
  39177. },
  39178. set: function (value) {
  39179. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39180. this._markAllSubMeshesAsMiscDirty();
  39181. },
  39182. enumerable: true,
  39183. configurable: true
  39184. });
  39185. StandardMaterial.prototype.needAlphaBlending = function () {
  39186. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39187. };
  39188. StandardMaterial.prototype.needAlphaTesting = function () {
  39189. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39190. };
  39191. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39192. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39193. };
  39194. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39195. return this._diffuseTexture;
  39196. };
  39197. /**
  39198. * Child classes can use it to update shaders
  39199. */
  39200. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39201. if (useInstances === void 0) { useInstances = false; }
  39202. if (subMesh.effect && this.isFrozen) {
  39203. if (this._wasPreviouslyReady && subMesh.effect) {
  39204. return true;
  39205. }
  39206. }
  39207. if (!subMesh._materialDefines) {
  39208. subMesh._materialDefines = new StandardMaterialDefines();
  39209. }
  39210. var scene = this.getScene();
  39211. var defines = subMesh._materialDefines;
  39212. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39213. if (defines._renderId === scene.getRenderId()) {
  39214. return true;
  39215. }
  39216. }
  39217. var engine = scene.getEngine();
  39218. // Lights
  39219. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39220. // Textures
  39221. if (defines._areTexturesDirty) {
  39222. defines._needUVs = false;
  39223. defines.MAINUV1 = false;
  39224. defines.MAINUV2 = false;
  39225. if (scene.texturesEnabled) {
  39226. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39227. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39228. return false;
  39229. }
  39230. else {
  39231. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39232. }
  39233. }
  39234. else {
  39235. defines.DIFFUSE = false;
  39236. }
  39237. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39238. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39239. return false;
  39240. }
  39241. else {
  39242. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39243. }
  39244. }
  39245. else {
  39246. defines.AMBIENT = false;
  39247. }
  39248. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39249. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39250. return false;
  39251. }
  39252. else {
  39253. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39254. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39255. }
  39256. }
  39257. else {
  39258. defines.OPACITY = false;
  39259. }
  39260. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39261. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39262. return false;
  39263. }
  39264. else {
  39265. defines._needNormals = true;
  39266. defines.REFLECTION = true;
  39267. defines.ROUGHNESS = (this._roughness > 0);
  39268. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39269. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39270. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39271. switch (this._reflectionTexture.coordinatesMode) {
  39272. case BABYLON.Texture.CUBIC_MODE:
  39273. case BABYLON.Texture.INVCUBIC_MODE:
  39274. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39275. break;
  39276. case BABYLON.Texture.EXPLICIT_MODE:
  39277. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39278. break;
  39279. case BABYLON.Texture.PLANAR_MODE:
  39280. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39281. break;
  39282. case BABYLON.Texture.PROJECTION_MODE:
  39283. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39284. break;
  39285. case BABYLON.Texture.SKYBOX_MODE:
  39286. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39287. break;
  39288. case BABYLON.Texture.SPHERICAL_MODE:
  39289. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39290. break;
  39291. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39292. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39293. break;
  39294. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39295. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39296. break;
  39297. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39298. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39299. break;
  39300. }
  39301. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39302. }
  39303. }
  39304. else {
  39305. defines.REFLECTION = false;
  39306. }
  39307. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39308. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39309. return false;
  39310. }
  39311. else {
  39312. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39313. }
  39314. }
  39315. else {
  39316. defines.EMISSIVE = false;
  39317. }
  39318. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39319. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39320. return false;
  39321. }
  39322. else {
  39323. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39324. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39325. }
  39326. }
  39327. else {
  39328. defines.LIGHTMAP = false;
  39329. }
  39330. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39331. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39332. return false;
  39333. }
  39334. else {
  39335. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39336. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39337. }
  39338. }
  39339. else {
  39340. defines.SPECULAR = false;
  39341. }
  39342. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39343. // Bump texure can not be not blocking.
  39344. if (!this._bumpTexture.isReady()) {
  39345. return false;
  39346. }
  39347. else {
  39348. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39349. defines.PARALLAX = this._useParallax;
  39350. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39351. }
  39352. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39353. }
  39354. else {
  39355. defines.BUMP = false;
  39356. }
  39357. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39358. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39359. return false;
  39360. }
  39361. else {
  39362. defines._needUVs = true;
  39363. defines.REFRACTION = true;
  39364. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39365. }
  39366. }
  39367. else {
  39368. defines.REFRACTION = false;
  39369. }
  39370. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39371. }
  39372. else {
  39373. defines.DIFFUSE = false;
  39374. defines.AMBIENT = false;
  39375. defines.OPACITY = false;
  39376. defines.REFLECTION = false;
  39377. defines.EMISSIVE = false;
  39378. defines.LIGHTMAP = false;
  39379. defines.BUMP = false;
  39380. defines.REFRACTION = false;
  39381. }
  39382. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39383. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39384. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39385. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39386. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39387. }
  39388. if (defines._areImageProcessingDirty) {
  39389. if (!this._imageProcessingConfiguration.isReady()) {
  39390. return false;
  39391. }
  39392. this._imageProcessingConfiguration.prepareDefines(defines);
  39393. }
  39394. if (defines._areFresnelDirty) {
  39395. if (StandardMaterial.FresnelEnabled) {
  39396. // Fresnel
  39397. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39398. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39399. this._reflectionFresnelParameters) {
  39400. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39401. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39402. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39403. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39404. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39405. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39406. defines._needNormals = true;
  39407. defines.FRESNEL = true;
  39408. }
  39409. }
  39410. else {
  39411. defines.FRESNEL = false;
  39412. }
  39413. }
  39414. // Misc.
  39415. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39416. // Attribs
  39417. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39418. // Values that need to be evaluated on every frame
  39419. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39420. // Get correct effect
  39421. if (defines.isDirty) {
  39422. defines.markAsProcessed();
  39423. scene.resetCachedMaterial();
  39424. // Fallbacks
  39425. var fallbacks = new BABYLON.EffectFallbacks();
  39426. if (defines.REFLECTION) {
  39427. fallbacks.addFallback(0, "REFLECTION");
  39428. }
  39429. if (defines.SPECULAR) {
  39430. fallbacks.addFallback(0, "SPECULAR");
  39431. }
  39432. if (defines.BUMP) {
  39433. fallbacks.addFallback(0, "BUMP");
  39434. }
  39435. if (defines.PARALLAX) {
  39436. fallbacks.addFallback(1, "PARALLAX");
  39437. }
  39438. if (defines.PARALLAXOCCLUSION) {
  39439. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39440. }
  39441. if (defines.SPECULAROVERALPHA) {
  39442. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39443. }
  39444. if (defines.FOG) {
  39445. fallbacks.addFallback(1, "FOG");
  39446. }
  39447. if (defines.POINTSIZE) {
  39448. fallbacks.addFallback(0, "POINTSIZE");
  39449. }
  39450. if (defines.LOGARITHMICDEPTH) {
  39451. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39452. }
  39453. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39454. if (defines.SPECULARTERM) {
  39455. fallbacks.addFallback(0, "SPECULARTERM");
  39456. }
  39457. if (defines.DIFFUSEFRESNEL) {
  39458. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39459. }
  39460. if (defines.OPACITYFRESNEL) {
  39461. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39462. }
  39463. if (defines.REFLECTIONFRESNEL) {
  39464. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39465. }
  39466. if (defines.EMISSIVEFRESNEL) {
  39467. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39468. }
  39469. if (defines.FRESNEL) {
  39470. fallbacks.addFallback(4, "FRESNEL");
  39471. }
  39472. //Attributes
  39473. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39474. if (defines.NORMAL) {
  39475. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39476. }
  39477. if (defines.UV1) {
  39478. attribs.push(BABYLON.VertexBuffer.UVKind);
  39479. }
  39480. if (defines.UV2) {
  39481. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39482. }
  39483. if (defines.VERTEXCOLOR) {
  39484. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39485. }
  39486. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39487. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39488. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39489. var shaderName = "default";
  39490. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39491. "vFogInfos", "vFogColor", "pointSize",
  39492. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39493. "mBones",
  39494. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39495. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39496. "vReflectionPosition", "vReflectionSize",
  39497. "logarithmicDepthConstant", "vTangentSpaceParams"
  39498. ];
  39499. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39500. var uniformBuffers = ["Material", "Scene"];
  39501. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39502. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39503. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39504. uniformsNames: uniforms,
  39505. uniformBuffersNames: uniformBuffers,
  39506. samplers: samplers,
  39507. defines: defines,
  39508. maxSimultaneousLights: this._maxSimultaneousLights
  39509. });
  39510. if (this.customShaderNameResolve) {
  39511. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39512. }
  39513. var join = defines.toString();
  39514. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39515. attributes: attribs,
  39516. uniformsNames: uniforms,
  39517. uniformBuffersNames: uniformBuffers,
  39518. samplers: samplers,
  39519. defines: join,
  39520. fallbacks: fallbacks,
  39521. onCompiled: this.onCompiled,
  39522. onError: this.onError,
  39523. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39524. }, engine), defines);
  39525. this.buildUniformLayout();
  39526. }
  39527. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39528. return false;
  39529. }
  39530. defines._renderId = scene.getRenderId();
  39531. this._wasPreviouslyReady = true;
  39532. return true;
  39533. };
  39534. StandardMaterial.prototype.buildUniformLayout = function () {
  39535. // Order is important !
  39536. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39537. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39538. this._uniformBuffer.addUniform("opacityParts", 4);
  39539. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39540. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39541. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39542. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39543. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39544. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39545. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39546. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39547. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39548. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39549. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39550. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39551. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39552. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39553. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39554. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39555. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39556. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39557. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39558. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39559. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39560. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39561. this._uniformBuffer.addUniform("specularMatrix", 16);
  39562. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39563. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39564. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39565. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39566. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39567. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39568. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39569. this._uniformBuffer.addUniform("pointSize", 1);
  39570. this._uniformBuffer.create();
  39571. };
  39572. StandardMaterial.prototype.unbind = function () {
  39573. if (this._activeEffect) {
  39574. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39575. this._activeEffect.setTexture("reflection2DSampler", null);
  39576. }
  39577. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39578. this._activeEffect.setTexture("refraction2DSampler", null);
  39579. }
  39580. }
  39581. _super.prototype.unbind.call(this);
  39582. };
  39583. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39584. var scene = this.getScene();
  39585. var defines = subMesh._materialDefines;
  39586. if (!defines) {
  39587. return;
  39588. }
  39589. var effect = subMesh.effect;
  39590. if (!effect) {
  39591. return;
  39592. }
  39593. this._activeEffect = effect;
  39594. // Matrices
  39595. this.bindOnlyWorldMatrix(world);
  39596. // Normal Matrix
  39597. if (defines.OBJECTSPACE_NORMALMAP) {
  39598. world.toNormalMatrix(this._normalMatrix);
  39599. this.bindOnlyNormalMatrix(this._normalMatrix);
  39600. }
  39601. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39602. // Bones
  39603. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39604. if (mustRebind) {
  39605. this._uniformBuffer.bindToEffect(effect, "Material");
  39606. this.bindViewProjection(effect);
  39607. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39608. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39609. // Fresnel
  39610. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39611. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39612. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39613. }
  39614. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39615. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39616. }
  39617. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39618. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39619. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39620. }
  39621. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39622. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39623. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39624. }
  39625. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39626. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39627. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39628. }
  39629. }
  39630. // Textures
  39631. if (scene.texturesEnabled) {
  39632. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39633. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39634. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39635. }
  39636. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39637. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39638. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39639. }
  39640. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39641. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39642. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39643. }
  39644. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39645. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39646. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39647. if (this._reflectionTexture.boundingBoxSize) {
  39648. var cubeTexture = this._reflectionTexture;
  39649. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39650. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39651. }
  39652. }
  39653. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39654. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39655. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39656. }
  39657. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39658. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39659. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39660. }
  39661. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39662. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39663. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39664. }
  39665. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39666. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39667. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39668. if (scene._mirroredCameraPosition) {
  39669. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39670. }
  39671. else {
  39672. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39673. }
  39674. }
  39675. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39676. var depth = 1.0;
  39677. if (!this._refractionTexture.isCube) {
  39678. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39679. if (this._refractionTexture.depth) {
  39680. depth = this._refractionTexture.depth;
  39681. }
  39682. }
  39683. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39684. }
  39685. }
  39686. // Point size
  39687. if (this.pointsCloud) {
  39688. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39689. }
  39690. if (defines.SPECULARTERM) {
  39691. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39692. }
  39693. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39694. // Diffuse
  39695. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39696. }
  39697. // Textures
  39698. if (scene.texturesEnabled) {
  39699. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39700. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39701. }
  39702. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39703. effect.setTexture("ambientSampler", this._ambientTexture);
  39704. }
  39705. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39706. effect.setTexture("opacitySampler", this._opacityTexture);
  39707. }
  39708. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39709. if (this._reflectionTexture.isCube) {
  39710. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39711. }
  39712. else {
  39713. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39714. }
  39715. }
  39716. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39717. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39718. }
  39719. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39720. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39721. }
  39722. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39723. effect.setTexture("specularSampler", this._specularTexture);
  39724. }
  39725. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39726. effect.setTexture("bumpSampler", this._bumpTexture);
  39727. }
  39728. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39729. var depth = 1.0;
  39730. if (this._refractionTexture.isCube) {
  39731. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39732. }
  39733. else {
  39734. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39735. }
  39736. }
  39737. }
  39738. // Clip plane
  39739. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39740. // Colors
  39741. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39742. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39743. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39744. }
  39745. if (mustRebind || !this.isFrozen) {
  39746. // Lights
  39747. if (scene.lightsEnabled && !this._disableLighting) {
  39748. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39749. }
  39750. // View
  39751. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39752. this.bindView(effect);
  39753. }
  39754. // Fog
  39755. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39756. // Morph targets
  39757. if (defines.NUM_MORPH_INFLUENCERS) {
  39758. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39759. }
  39760. // Log. depth
  39761. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39762. // image processing
  39763. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39764. this._imageProcessingConfiguration.bind(this._activeEffect);
  39765. }
  39766. }
  39767. this._uniformBuffer.update();
  39768. this._afterBind(mesh, this._activeEffect);
  39769. };
  39770. StandardMaterial.prototype.getAnimatables = function () {
  39771. var results = [];
  39772. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39773. results.push(this._diffuseTexture);
  39774. }
  39775. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39776. results.push(this._ambientTexture);
  39777. }
  39778. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39779. results.push(this._opacityTexture);
  39780. }
  39781. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39782. results.push(this._reflectionTexture);
  39783. }
  39784. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39785. results.push(this._emissiveTexture);
  39786. }
  39787. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39788. results.push(this._specularTexture);
  39789. }
  39790. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39791. results.push(this._bumpTexture);
  39792. }
  39793. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39794. results.push(this._lightmapTexture);
  39795. }
  39796. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39797. results.push(this._refractionTexture);
  39798. }
  39799. return results;
  39800. };
  39801. StandardMaterial.prototype.getActiveTextures = function () {
  39802. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39803. if (this._diffuseTexture) {
  39804. activeTextures.push(this._diffuseTexture);
  39805. }
  39806. if (this._ambientTexture) {
  39807. activeTextures.push(this._ambientTexture);
  39808. }
  39809. if (this._opacityTexture) {
  39810. activeTextures.push(this._opacityTexture);
  39811. }
  39812. if (this._reflectionTexture) {
  39813. activeTextures.push(this._reflectionTexture);
  39814. }
  39815. if (this._emissiveTexture) {
  39816. activeTextures.push(this._emissiveTexture);
  39817. }
  39818. if (this._specularTexture) {
  39819. activeTextures.push(this._specularTexture);
  39820. }
  39821. if (this._bumpTexture) {
  39822. activeTextures.push(this._bumpTexture);
  39823. }
  39824. if (this._lightmapTexture) {
  39825. activeTextures.push(this._lightmapTexture);
  39826. }
  39827. if (this._refractionTexture) {
  39828. activeTextures.push(this._refractionTexture);
  39829. }
  39830. return activeTextures;
  39831. };
  39832. StandardMaterial.prototype.hasTexture = function (texture) {
  39833. if (_super.prototype.hasTexture.call(this, texture)) {
  39834. return true;
  39835. }
  39836. if (this._diffuseTexture === texture) {
  39837. return true;
  39838. }
  39839. if (this._ambientTexture === texture) {
  39840. return true;
  39841. }
  39842. if (this._opacityTexture === texture) {
  39843. return true;
  39844. }
  39845. if (this._reflectionTexture === texture) {
  39846. return true;
  39847. }
  39848. if (this._emissiveTexture === texture) {
  39849. return true;
  39850. }
  39851. if (this._specularTexture === texture) {
  39852. return true;
  39853. }
  39854. if (this._bumpTexture === texture) {
  39855. return true;
  39856. }
  39857. if (this._lightmapTexture === texture) {
  39858. return true;
  39859. }
  39860. if (this._refractionTexture === texture) {
  39861. return true;
  39862. }
  39863. return false;
  39864. };
  39865. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39866. if (forceDisposeTextures) {
  39867. if (this._diffuseTexture) {
  39868. this._diffuseTexture.dispose();
  39869. }
  39870. if (this._ambientTexture) {
  39871. this._ambientTexture.dispose();
  39872. }
  39873. if (this._opacityTexture) {
  39874. this._opacityTexture.dispose();
  39875. }
  39876. if (this._reflectionTexture) {
  39877. this._reflectionTexture.dispose();
  39878. }
  39879. if (this._emissiveTexture) {
  39880. this._emissiveTexture.dispose();
  39881. }
  39882. if (this._specularTexture) {
  39883. this._specularTexture.dispose();
  39884. }
  39885. if (this._bumpTexture) {
  39886. this._bumpTexture.dispose();
  39887. }
  39888. if (this._lightmapTexture) {
  39889. this._lightmapTexture.dispose();
  39890. }
  39891. if (this._refractionTexture) {
  39892. this._refractionTexture.dispose();
  39893. }
  39894. }
  39895. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39896. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39897. }
  39898. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39899. };
  39900. StandardMaterial.prototype.clone = function (name) {
  39901. var _this = this;
  39902. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39903. result.name = name;
  39904. result.id = name;
  39905. return result;
  39906. };
  39907. StandardMaterial.prototype.serialize = function () {
  39908. return BABYLON.SerializationHelper.Serialize(this);
  39909. };
  39910. // Statics
  39911. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39912. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39913. };
  39914. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39915. get: function () {
  39916. return StandardMaterial._DiffuseTextureEnabled;
  39917. },
  39918. set: function (value) {
  39919. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39920. return;
  39921. }
  39922. StandardMaterial._DiffuseTextureEnabled = value;
  39923. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39924. },
  39925. enumerable: true,
  39926. configurable: true
  39927. });
  39928. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39929. get: function () {
  39930. return StandardMaterial._AmbientTextureEnabled;
  39931. },
  39932. set: function (value) {
  39933. if (StandardMaterial._AmbientTextureEnabled === value) {
  39934. return;
  39935. }
  39936. StandardMaterial._AmbientTextureEnabled = value;
  39937. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39938. },
  39939. enumerable: true,
  39940. configurable: true
  39941. });
  39942. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39943. get: function () {
  39944. return StandardMaterial._OpacityTextureEnabled;
  39945. },
  39946. set: function (value) {
  39947. if (StandardMaterial._OpacityTextureEnabled === value) {
  39948. return;
  39949. }
  39950. StandardMaterial._OpacityTextureEnabled = value;
  39951. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39952. },
  39953. enumerable: true,
  39954. configurable: true
  39955. });
  39956. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39957. get: function () {
  39958. return StandardMaterial._ReflectionTextureEnabled;
  39959. },
  39960. set: function (value) {
  39961. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39962. return;
  39963. }
  39964. StandardMaterial._ReflectionTextureEnabled = value;
  39965. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39966. },
  39967. enumerable: true,
  39968. configurable: true
  39969. });
  39970. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39971. get: function () {
  39972. return StandardMaterial._EmissiveTextureEnabled;
  39973. },
  39974. set: function (value) {
  39975. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39976. return;
  39977. }
  39978. StandardMaterial._EmissiveTextureEnabled = value;
  39979. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39980. },
  39981. enumerable: true,
  39982. configurable: true
  39983. });
  39984. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39985. get: function () {
  39986. return StandardMaterial._SpecularTextureEnabled;
  39987. },
  39988. set: function (value) {
  39989. if (StandardMaterial._SpecularTextureEnabled === value) {
  39990. return;
  39991. }
  39992. StandardMaterial._SpecularTextureEnabled = value;
  39993. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39994. },
  39995. enumerable: true,
  39996. configurable: true
  39997. });
  39998. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39999. get: function () {
  40000. return StandardMaterial._BumpTextureEnabled;
  40001. },
  40002. set: function (value) {
  40003. if (StandardMaterial._BumpTextureEnabled === value) {
  40004. return;
  40005. }
  40006. StandardMaterial._BumpTextureEnabled = value;
  40007. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40008. },
  40009. enumerable: true,
  40010. configurable: true
  40011. });
  40012. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40013. get: function () {
  40014. return StandardMaterial._LightmapTextureEnabled;
  40015. },
  40016. set: function (value) {
  40017. if (StandardMaterial._LightmapTextureEnabled === value) {
  40018. return;
  40019. }
  40020. StandardMaterial._LightmapTextureEnabled = value;
  40021. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40022. },
  40023. enumerable: true,
  40024. configurable: true
  40025. });
  40026. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40027. get: function () {
  40028. return StandardMaterial._RefractionTextureEnabled;
  40029. },
  40030. set: function (value) {
  40031. if (StandardMaterial._RefractionTextureEnabled === value) {
  40032. return;
  40033. }
  40034. StandardMaterial._RefractionTextureEnabled = value;
  40035. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40036. },
  40037. enumerable: true,
  40038. configurable: true
  40039. });
  40040. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40041. get: function () {
  40042. return StandardMaterial._ColorGradingTextureEnabled;
  40043. },
  40044. set: function (value) {
  40045. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40046. return;
  40047. }
  40048. StandardMaterial._ColorGradingTextureEnabled = value;
  40049. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40050. },
  40051. enumerable: true,
  40052. configurable: true
  40053. });
  40054. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40055. get: function () {
  40056. return StandardMaterial._FresnelEnabled;
  40057. },
  40058. set: function (value) {
  40059. if (StandardMaterial._FresnelEnabled === value) {
  40060. return;
  40061. }
  40062. StandardMaterial._FresnelEnabled = value;
  40063. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40064. },
  40065. enumerable: true,
  40066. configurable: true
  40067. });
  40068. // Flags used to enable or disable a type of texture for all Standard Materials
  40069. StandardMaterial._DiffuseTextureEnabled = true;
  40070. StandardMaterial._AmbientTextureEnabled = true;
  40071. StandardMaterial._OpacityTextureEnabled = true;
  40072. StandardMaterial._ReflectionTextureEnabled = true;
  40073. StandardMaterial._EmissiveTextureEnabled = true;
  40074. StandardMaterial._SpecularTextureEnabled = true;
  40075. StandardMaterial._BumpTextureEnabled = true;
  40076. StandardMaterial._LightmapTextureEnabled = true;
  40077. StandardMaterial._RefractionTextureEnabled = true;
  40078. StandardMaterial._ColorGradingTextureEnabled = true;
  40079. StandardMaterial._FresnelEnabled = true;
  40080. __decorate([
  40081. BABYLON.serializeAsTexture("diffuseTexture")
  40082. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40083. __decorate([
  40084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40085. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40086. __decorate([
  40087. BABYLON.serializeAsTexture("ambientTexture")
  40088. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40089. __decorate([
  40090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40091. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40092. __decorate([
  40093. BABYLON.serializeAsTexture("opacityTexture")
  40094. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40095. __decorate([
  40096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40097. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40098. __decorate([
  40099. BABYLON.serializeAsTexture("reflectionTexture")
  40100. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40101. __decorate([
  40102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40103. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40104. __decorate([
  40105. BABYLON.serializeAsTexture("emissiveTexture")
  40106. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40107. __decorate([
  40108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40109. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40110. __decorate([
  40111. BABYLON.serializeAsTexture("specularTexture")
  40112. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40113. __decorate([
  40114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40115. ], StandardMaterial.prototype, "specularTexture", void 0);
  40116. __decorate([
  40117. BABYLON.serializeAsTexture("bumpTexture")
  40118. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40119. __decorate([
  40120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40121. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40122. __decorate([
  40123. BABYLON.serializeAsTexture("lightmapTexture")
  40124. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40125. __decorate([
  40126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40127. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40128. __decorate([
  40129. BABYLON.serializeAsTexture("refractionTexture")
  40130. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40131. __decorate([
  40132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40133. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40134. __decorate([
  40135. BABYLON.serializeAsColor3("ambient")
  40136. ], StandardMaterial.prototype, "ambientColor", void 0);
  40137. __decorate([
  40138. BABYLON.serializeAsColor3("diffuse")
  40139. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40140. __decorate([
  40141. BABYLON.serializeAsColor3("specular")
  40142. ], StandardMaterial.prototype, "specularColor", void 0);
  40143. __decorate([
  40144. BABYLON.serializeAsColor3("emissive")
  40145. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40146. __decorate([
  40147. BABYLON.serialize()
  40148. ], StandardMaterial.prototype, "specularPower", void 0);
  40149. __decorate([
  40150. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40151. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40152. __decorate([
  40153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40154. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40155. __decorate([
  40156. BABYLON.serialize("useEmissiveAsIllumination")
  40157. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40158. __decorate([
  40159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40160. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40161. __decorate([
  40162. BABYLON.serialize("linkEmissiveWithDiffuse")
  40163. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40164. __decorate([
  40165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40166. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40167. __decorate([
  40168. BABYLON.serialize("useSpecularOverAlpha")
  40169. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40170. __decorate([
  40171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40172. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40173. __decorate([
  40174. BABYLON.serialize("useReflectionOverAlpha")
  40175. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40176. __decorate([
  40177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40178. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40179. __decorate([
  40180. BABYLON.serialize("disableLighting")
  40181. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40182. __decorate([
  40183. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40184. ], StandardMaterial.prototype, "disableLighting", void 0);
  40185. __decorate([
  40186. BABYLON.serialize("useObjectSpaceNormalMap")
  40187. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40188. __decorate([
  40189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40190. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40191. __decorate([
  40192. BABYLON.serialize("useParallax")
  40193. ], StandardMaterial.prototype, "_useParallax", void 0);
  40194. __decorate([
  40195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40196. ], StandardMaterial.prototype, "useParallax", void 0);
  40197. __decorate([
  40198. BABYLON.serialize("useParallaxOcclusion")
  40199. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40200. __decorate([
  40201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40202. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40203. __decorate([
  40204. BABYLON.serialize()
  40205. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40206. __decorate([
  40207. BABYLON.serialize("roughness")
  40208. ], StandardMaterial.prototype, "_roughness", void 0);
  40209. __decorate([
  40210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40211. ], StandardMaterial.prototype, "roughness", void 0);
  40212. __decorate([
  40213. BABYLON.serialize()
  40214. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40215. __decorate([
  40216. BABYLON.serialize()
  40217. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40218. __decorate([
  40219. BABYLON.serialize("useLightmapAsShadowmap")
  40220. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40221. __decorate([
  40222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40223. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40224. __decorate([
  40225. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40226. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40227. __decorate([
  40228. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40229. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40230. __decorate([
  40231. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40232. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40233. __decorate([
  40234. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40235. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40236. __decorate([
  40237. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40238. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40239. __decorate([
  40240. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40241. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40242. __decorate([
  40243. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40244. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40245. __decorate([
  40246. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40247. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40248. __decorate([
  40249. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40250. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40251. __decorate([
  40252. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40253. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40254. __decorate([
  40255. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40256. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40257. __decorate([
  40258. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40259. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40260. __decorate([
  40261. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40262. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40263. __decorate([
  40264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40265. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40266. __decorate([
  40267. BABYLON.serialize("maxSimultaneousLights")
  40268. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40269. __decorate([
  40270. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40271. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40272. __decorate([
  40273. BABYLON.serialize("invertNormalMapX")
  40274. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40275. __decorate([
  40276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40277. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40278. __decorate([
  40279. BABYLON.serialize("invertNormalMapY")
  40280. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40281. __decorate([
  40282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40283. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40284. __decorate([
  40285. BABYLON.serialize("twoSidedLighting")
  40286. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40287. __decorate([
  40288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40289. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40290. __decorate([
  40291. BABYLON.serialize()
  40292. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40293. return StandardMaterial;
  40294. }(BABYLON.PushMaterial));
  40295. BABYLON.StandardMaterial = StandardMaterial;
  40296. })(BABYLON || (BABYLON = {}));
  40297. //# sourceMappingURL=babylon.standardMaterial.js.map
  40298. var BABYLON;
  40299. (function (BABYLON) {
  40300. /**
  40301. * Manages the defines for the PBR Material.
  40302. */
  40303. var PBRMaterialDefines = /** @class */ (function (_super) {
  40304. __extends(PBRMaterialDefines, _super);
  40305. /**
  40306. * Initializes the PBR Material defines.
  40307. */
  40308. function PBRMaterialDefines() {
  40309. var _this = _super.call(this) || this;
  40310. _this.PBR = true;
  40311. _this.MAINUV1 = false;
  40312. _this.MAINUV2 = false;
  40313. _this.UV1 = false;
  40314. _this.UV2 = false;
  40315. _this.ALBEDO = false;
  40316. _this.ALBEDODIRECTUV = 0;
  40317. _this.VERTEXCOLOR = false;
  40318. _this.AMBIENT = false;
  40319. _this.AMBIENTDIRECTUV = 0;
  40320. _this.AMBIENTINGRAYSCALE = false;
  40321. _this.OPACITY = false;
  40322. _this.VERTEXALPHA = false;
  40323. _this.OPACITYDIRECTUV = 0;
  40324. _this.OPACITYRGB = false;
  40325. _this.ALPHATEST = false;
  40326. _this.DEPTHPREPASS = false;
  40327. _this.ALPHABLEND = false;
  40328. _this.ALPHAFROMALBEDO = false;
  40329. _this.ALPHATESTVALUE = 0.5;
  40330. _this.SPECULAROVERALPHA = false;
  40331. _this.RADIANCEOVERALPHA = false;
  40332. _this.ALPHAFRESNEL = false;
  40333. _this.LINEARALPHAFRESNEL = false;
  40334. _this.PREMULTIPLYALPHA = false;
  40335. _this.EMISSIVE = false;
  40336. _this.EMISSIVEDIRECTUV = 0;
  40337. _this.REFLECTIVITY = false;
  40338. _this.REFLECTIVITYDIRECTUV = 0;
  40339. _this.SPECULARTERM = false;
  40340. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40341. _this.MICROSURFACEAUTOMATIC = false;
  40342. _this.LODBASEDMICROSFURACE = false;
  40343. _this.MICROSURFACEMAP = false;
  40344. _this.MICROSURFACEMAPDIRECTUV = 0;
  40345. _this.METALLICWORKFLOW = false;
  40346. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40347. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40348. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40349. _this.AOSTOREINMETALMAPRED = false;
  40350. _this.ENVIRONMENTBRDF = false;
  40351. _this.NORMAL = false;
  40352. _this.TANGENT = false;
  40353. _this.BUMP = false;
  40354. _this.BUMPDIRECTUV = 0;
  40355. _this.OBJECTSPACE_NORMALMAP = false;
  40356. _this.PARALLAX = false;
  40357. _this.PARALLAXOCCLUSION = false;
  40358. _this.NORMALXYSCALE = true;
  40359. _this.LIGHTMAP = false;
  40360. _this.LIGHTMAPDIRECTUV = 0;
  40361. _this.USELIGHTMAPASSHADOWMAP = false;
  40362. _this.REFLECTION = false;
  40363. _this.REFLECTIONMAP_3D = false;
  40364. _this.REFLECTIONMAP_SPHERICAL = false;
  40365. _this.REFLECTIONMAP_PLANAR = false;
  40366. _this.REFLECTIONMAP_CUBIC = false;
  40367. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40368. _this.REFLECTIONMAP_PROJECTION = false;
  40369. _this.REFLECTIONMAP_SKYBOX = false;
  40370. _this.REFLECTIONMAP_EXPLICIT = false;
  40371. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40372. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40373. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40374. _this.INVERTCUBICMAP = false;
  40375. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40376. _this.USESPHERICALINVERTEX = false;
  40377. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40378. _this.LODINREFLECTIONALPHA = false;
  40379. _this.GAMMAREFLECTION = false;
  40380. _this.RADIANCEOCCLUSION = false;
  40381. _this.HORIZONOCCLUSION = false;
  40382. _this.REFRACTION = false;
  40383. _this.REFRACTIONMAP_3D = false;
  40384. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40385. _this.LODINREFRACTIONALPHA = false;
  40386. _this.GAMMAREFRACTION = false;
  40387. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40388. _this.INSTANCES = false;
  40389. _this.NUM_BONE_INFLUENCERS = 0;
  40390. _this.BonesPerMesh = 0;
  40391. _this.NONUNIFORMSCALING = false;
  40392. _this.MORPHTARGETS = false;
  40393. _this.MORPHTARGETS_NORMAL = false;
  40394. _this.MORPHTARGETS_TANGENT = false;
  40395. _this.NUM_MORPH_INFLUENCERS = 0;
  40396. _this.IMAGEPROCESSING = false;
  40397. _this.VIGNETTE = false;
  40398. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40399. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40400. _this.TONEMAPPING = false;
  40401. _this.CONTRAST = false;
  40402. _this.COLORCURVES = false;
  40403. _this.COLORGRADING = false;
  40404. _this.COLORGRADING3D = false;
  40405. _this.SAMPLER3DGREENDEPTH = false;
  40406. _this.SAMPLER3DBGRMAP = false;
  40407. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40408. _this.EXPOSURE = false;
  40409. _this.GRAIN = false;
  40410. _this.USEPHYSICALLIGHTFALLOFF = false;
  40411. _this.TWOSIDEDLIGHTING = false;
  40412. _this.SHADOWFLOAT = false;
  40413. _this.CLIPPLANE = false;
  40414. _this.POINTSIZE = false;
  40415. _this.FOG = false;
  40416. _this.LOGARITHMICDEPTH = false;
  40417. _this.FORCENORMALFORWARD = false;
  40418. _this.rebuild();
  40419. return _this;
  40420. }
  40421. /**
  40422. * Resets the PBR Material defines.
  40423. */
  40424. PBRMaterialDefines.prototype.reset = function () {
  40425. _super.prototype.reset.call(this);
  40426. this.ALPHATESTVALUE = 0.5;
  40427. this.PBR = true;
  40428. };
  40429. return PBRMaterialDefines;
  40430. }(BABYLON.MaterialDefines));
  40431. /**
  40432. * The Physically based material base class of BJS.
  40433. *
  40434. * This offers the main features of a standard PBR material.
  40435. * For more information, please refer to the documentation :
  40436. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40437. */
  40438. var PBRBaseMaterial = /** @class */ (function (_super) {
  40439. __extends(PBRBaseMaterial, _super);
  40440. /**
  40441. * Instantiates a new PBRMaterial instance.
  40442. *
  40443. * @param name The material name
  40444. * @param scene The scene the material will be use in.
  40445. */
  40446. function PBRBaseMaterial(name, scene) {
  40447. var _this = _super.call(this, name, scene) || this;
  40448. /**
  40449. * Intensity of the direct lights e.g. the four lights available in your scene.
  40450. * This impacts both the direct diffuse and specular highlights.
  40451. */
  40452. _this._directIntensity = 1.0;
  40453. /**
  40454. * Intensity of the emissive part of the material.
  40455. * This helps controlling the emissive effect without modifying the emissive color.
  40456. */
  40457. _this._emissiveIntensity = 1.0;
  40458. /**
  40459. * Intensity of the environment e.g. how much the environment will light the object
  40460. * either through harmonics for rough material or through the refelction for shiny ones.
  40461. */
  40462. _this._environmentIntensity = 1.0;
  40463. /**
  40464. * This is a special control allowing the reduction of the specular highlights coming from the
  40465. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40466. */
  40467. _this._specularIntensity = 1.0;
  40468. /**
  40469. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40470. */
  40471. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40472. /**
  40473. * Debug Control allowing disabling the bump map on this material.
  40474. */
  40475. _this._disableBumpMap = false;
  40476. /**
  40477. * AKA Occlusion Texture Intensity in other nomenclature.
  40478. */
  40479. _this._ambientTextureStrength = 1.0;
  40480. /**
  40481. * The color of a material in ambient lighting.
  40482. */
  40483. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40484. /**
  40485. * AKA Diffuse Color in other nomenclature.
  40486. */
  40487. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40488. /**
  40489. * AKA Specular Color in other nomenclature.
  40490. */
  40491. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40492. /**
  40493. * The color applied when light is reflected from a material.
  40494. */
  40495. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40496. /**
  40497. * The color applied when light is emitted from a material.
  40498. */
  40499. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40500. /**
  40501. * AKA Glossiness in other nomenclature.
  40502. */
  40503. _this._microSurface = 0.9;
  40504. /**
  40505. * source material index of refraction (IOR)' / 'destination material IOR.
  40506. */
  40507. _this._indexOfRefraction = 0.66;
  40508. /**
  40509. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40510. */
  40511. _this._invertRefractionY = false;
  40512. /**
  40513. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40514. * Materials half opaque for instance using refraction could benefit from this control.
  40515. */
  40516. _this._linkRefractionWithTransparency = false;
  40517. /**
  40518. * Specifies that the material will use the light map as a show map.
  40519. */
  40520. _this._useLightmapAsShadowmap = false;
  40521. /**
  40522. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40523. * makes the reflect vector face the model (under horizon).
  40524. */
  40525. _this._useHorizonOcclusion = true;
  40526. /**
  40527. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40528. * too much the area relying on ambient texture to define their ambient occlusion.
  40529. */
  40530. _this._useRadianceOcclusion = true;
  40531. /**
  40532. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40533. */
  40534. _this._useAlphaFromAlbedoTexture = false;
  40535. /**
  40536. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40537. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40538. */
  40539. _this._useSpecularOverAlpha = true;
  40540. /**
  40541. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40542. */
  40543. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40544. /**
  40545. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40546. */
  40547. _this._useRoughnessFromMetallicTextureAlpha = true;
  40548. /**
  40549. * Specifies if the metallic texture contains the roughness information in its green channel.
  40550. */
  40551. _this._useRoughnessFromMetallicTextureGreen = false;
  40552. /**
  40553. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40554. */
  40555. _this._useMetallnessFromMetallicTextureBlue = false;
  40556. /**
  40557. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40558. */
  40559. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40560. /**
  40561. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40562. */
  40563. _this._useAmbientInGrayScale = false;
  40564. /**
  40565. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40566. * The material will try to infer what glossiness each pixel should be.
  40567. */
  40568. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40569. /**
  40570. * BJS is using an harcoded light falloff based on a manually sets up range.
  40571. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40572. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40573. */
  40574. _this._usePhysicalLightFalloff = true;
  40575. /**
  40576. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40577. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40578. */
  40579. _this._useRadianceOverAlpha = true;
  40580. /**
  40581. * Allows using an object space normal map (instead of tangent space).
  40582. */
  40583. _this._useObjectSpaceNormalMap = false;
  40584. /**
  40585. * Allows using the bump map in parallax mode.
  40586. */
  40587. _this._useParallax = false;
  40588. /**
  40589. * Allows using the bump map in parallax occlusion mode.
  40590. */
  40591. _this._useParallaxOcclusion = false;
  40592. /**
  40593. * Controls the scale bias of the parallax mode.
  40594. */
  40595. _this._parallaxScaleBias = 0.05;
  40596. /**
  40597. * If sets to true, disables all the lights affecting the material.
  40598. */
  40599. _this._disableLighting = false;
  40600. /**
  40601. * Number of Simultaneous lights allowed on the material.
  40602. */
  40603. _this._maxSimultaneousLights = 4;
  40604. /**
  40605. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40606. */
  40607. _this._invertNormalMapX = false;
  40608. /**
  40609. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40610. */
  40611. _this._invertNormalMapY = false;
  40612. /**
  40613. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40614. */
  40615. _this._twoSidedLighting = false;
  40616. /**
  40617. * Defines the alpha limits in alpha test mode.
  40618. */
  40619. _this._alphaCutOff = 0.4;
  40620. /**
  40621. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40622. */
  40623. _this._forceAlphaTest = false;
  40624. /**
  40625. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40626. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40627. */
  40628. _this._useAlphaFresnel = false;
  40629. /**
  40630. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40631. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40632. */
  40633. _this._useLinearAlphaFresnel = false;
  40634. /**
  40635. * The transparency mode of the material.
  40636. */
  40637. _this._transparencyMode = null;
  40638. /**
  40639. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40640. * from cos thetav and roughness:
  40641. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40642. */
  40643. _this._environmentBRDFTexture = null;
  40644. /**
  40645. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40646. */
  40647. _this._forceIrradianceInFragment = false;
  40648. /**
  40649. * Force normal to face away from face.
  40650. */
  40651. _this._forceNormalForward = false;
  40652. /**
  40653. * Stores the available render targets.
  40654. */
  40655. _this._renderTargets = new BABYLON.SmartArray(16);
  40656. /**
  40657. * Sets the global ambient color for the material used in lighting calculations.
  40658. */
  40659. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40660. // Setup the default processing configuration to the scene.
  40661. _this._attachImageProcessingConfiguration(null);
  40662. _this.getRenderTargetTextures = function () {
  40663. _this._renderTargets.reset();
  40664. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40665. _this._renderTargets.push(_this._reflectionTexture);
  40666. }
  40667. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40668. _this._renderTargets.push(_this._refractionTexture);
  40669. }
  40670. return _this._renderTargets;
  40671. };
  40672. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40673. return _this;
  40674. }
  40675. /**
  40676. * Attaches a new image processing configuration to the PBR Material.
  40677. * @param configuration
  40678. */
  40679. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40680. var _this = this;
  40681. if (configuration === this._imageProcessingConfiguration) {
  40682. return;
  40683. }
  40684. // Detaches observer.
  40685. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40686. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40687. }
  40688. // Pick the scene configuration if needed.
  40689. if (!configuration) {
  40690. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40691. }
  40692. else {
  40693. this._imageProcessingConfiguration = configuration;
  40694. }
  40695. // Attaches observer.
  40696. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40697. _this._markAllSubMeshesAsImageProcessingDirty();
  40698. });
  40699. };
  40700. /**
  40701. * Gets the name of the material class.
  40702. */
  40703. PBRBaseMaterial.prototype.getClassName = function () {
  40704. return "PBRBaseMaterial";
  40705. };
  40706. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40707. /**
  40708. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40709. */
  40710. get: function () {
  40711. return this._useLogarithmicDepth;
  40712. },
  40713. /**
  40714. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40715. */
  40716. set: function (value) {
  40717. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40718. },
  40719. enumerable: true,
  40720. configurable: true
  40721. });
  40722. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40723. /**
  40724. * Gets the current transparency mode.
  40725. */
  40726. get: function () {
  40727. return this._transparencyMode;
  40728. },
  40729. /**
  40730. * Sets the transparency mode of the material.
  40731. */
  40732. set: function (value) {
  40733. if (this._transparencyMode === value) {
  40734. return;
  40735. }
  40736. this._transparencyMode = value;
  40737. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40738. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40739. },
  40740. enumerable: true,
  40741. configurable: true
  40742. });
  40743. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40744. /**
  40745. * Returns true if alpha blending should be disabled.
  40746. */
  40747. get: function () {
  40748. return (this._linkRefractionWithTransparency ||
  40749. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40750. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40751. },
  40752. enumerable: true,
  40753. configurable: true
  40754. });
  40755. /**
  40756. * Specifies whether or not this material should be rendered in alpha blend mode.
  40757. */
  40758. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40759. if (this._disableAlphaBlending) {
  40760. return false;
  40761. }
  40762. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40763. };
  40764. /**
  40765. * Specifies if the mesh will require alpha blending.
  40766. * @param mesh - BJS mesh.
  40767. */
  40768. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40769. if (this._disableAlphaBlending) {
  40770. return false;
  40771. }
  40772. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40773. };
  40774. /**
  40775. * Specifies whether or not this material should be rendered in alpha test mode.
  40776. */
  40777. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40778. if (this._forceAlphaTest) {
  40779. return true;
  40780. }
  40781. if (this._linkRefractionWithTransparency) {
  40782. return false;
  40783. }
  40784. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40785. };
  40786. /**
  40787. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40788. */
  40789. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40790. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40791. };
  40792. /**
  40793. * Gets the texture used for the alpha test.
  40794. */
  40795. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40796. return this._albedoTexture;
  40797. };
  40798. /**
  40799. * Specifies that the submesh is ready to be used.
  40800. * @param mesh - BJS mesh.
  40801. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40802. * @param useInstances - Specifies that instances should be used.
  40803. * @returns - boolean indicating that the submesh is ready or not.
  40804. */
  40805. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40806. if (subMesh.effect && this.isFrozen) {
  40807. if (this._wasPreviouslyReady) {
  40808. return true;
  40809. }
  40810. }
  40811. if (!subMesh._materialDefines) {
  40812. subMesh._materialDefines = new PBRMaterialDefines();
  40813. }
  40814. var defines = subMesh._materialDefines;
  40815. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40816. if (defines._renderId === this.getScene().getRenderId()) {
  40817. return true;
  40818. }
  40819. }
  40820. var scene = this.getScene();
  40821. var engine = scene.getEngine();
  40822. if (defines._areTexturesDirty) {
  40823. if (scene.texturesEnabled) {
  40824. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40825. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40826. return false;
  40827. }
  40828. }
  40829. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40830. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40831. return false;
  40832. }
  40833. }
  40834. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40835. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40836. return false;
  40837. }
  40838. }
  40839. var reflectionTexture = this._getReflectionTexture();
  40840. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40841. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40842. return false;
  40843. }
  40844. }
  40845. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40846. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40847. return false;
  40848. }
  40849. }
  40850. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40851. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40852. return false;
  40853. }
  40854. }
  40855. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40856. if (this._metallicTexture) {
  40857. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40858. return false;
  40859. }
  40860. }
  40861. else if (this._reflectivityTexture) {
  40862. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40863. return false;
  40864. }
  40865. }
  40866. if (this._microSurfaceTexture) {
  40867. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40868. return false;
  40869. }
  40870. }
  40871. }
  40872. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40873. // Bump texture cannot be not blocking.
  40874. if (!this._bumpTexture.isReady()) {
  40875. return false;
  40876. }
  40877. }
  40878. var refractionTexture = this._getRefractionTexture();
  40879. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40880. if (!refractionTexture.isReadyOrNotBlocking()) {
  40881. return false;
  40882. }
  40883. }
  40884. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40885. // This is blocking.
  40886. if (!this._environmentBRDFTexture.isReady()) {
  40887. return false;
  40888. }
  40889. }
  40890. }
  40891. }
  40892. if (defines._areImageProcessingDirty) {
  40893. if (!this._imageProcessingConfiguration.isReady()) {
  40894. return false;
  40895. }
  40896. }
  40897. if (!engine.getCaps().standardDerivatives) {
  40898. var bufferMesh = null;
  40899. if (mesh.getClassName() === "InstancedMesh") {
  40900. bufferMesh = mesh.sourceMesh;
  40901. }
  40902. else if (mesh.getClassName() === "Mesh") {
  40903. bufferMesh = mesh;
  40904. }
  40905. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40906. bufferMesh.createNormals(true);
  40907. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40908. }
  40909. }
  40910. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40911. if (effect) {
  40912. scene.resetCachedMaterial();
  40913. subMesh.setEffect(effect, defines);
  40914. this.buildUniformLayout();
  40915. }
  40916. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40917. return false;
  40918. }
  40919. defines._renderId = scene.getRenderId();
  40920. this._wasPreviouslyReady = true;
  40921. return true;
  40922. };
  40923. /**
  40924. * Specifies if the material uses metallic roughness workflow.
  40925. * @returns boolean specifiying if the material uses metallic roughness workflow.
  40926. */
  40927. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  40928. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  40929. return true;
  40930. }
  40931. return false;
  40932. };
  40933. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40934. if (onCompiled === void 0) { onCompiled = null; }
  40935. if (onError === void 0) { onError = null; }
  40936. if (useInstances === void 0) { useInstances = null; }
  40937. if (useClipPlane === void 0) { useClipPlane = null; }
  40938. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40939. if (!defines.isDirty) {
  40940. return null;
  40941. }
  40942. defines.markAsProcessed();
  40943. var scene = this.getScene();
  40944. var engine = scene.getEngine();
  40945. // Fallbacks
  40946. var fallbacks = new BABYLON.EffectFallbacks();
  40947. var fallbackRank = 0;
  40948. if (defines.USESPHERICALINVERTEX) {
  40949. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40950. }
  40951. if (defines.FOG) {
  40952. fallbacks.addFallback(fallbackRank, "FOG");
  40953. }
  40954. if (defines.POINTSIZE) {
  40955. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40956. }
  40957. if (defines.LOGARITHMICDEPTH) {
  40958. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40959. }
  40960. if (defines.PARALLAX) {
  40961. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40962. }
  40963. if (defines.PARALLAXOCCLUSION) {
  40964. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40965. }
  40966. if (defines.ENVIRONMENTBRDF) {
  40967. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40968. }
  40969. if (defines.TANGENT) {
  40970. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40971. }
  40972. if (defines.BUMP) {
  40973. fallbacks.addFallback(fallbackRank++, "BUMP");
  40974. }
  40975. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40976. if (defines.SPECULARTERM) {
  40977. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40978. }
  40979. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40980. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40981. }
  40982. if (defines.LIGHTMAP) {
  40983. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40984. }
  40985. if (defines.NORMAL) {
  40986. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40987. }
  40988. if (defines.AMBIENT) {
  40989. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40990. }
  40991. if (defines.EMISSIVE) {
  40992. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40993. }
  40994. if (defines.VERTEXCOLOR) {
  40995. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40996. }
  40997. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40998. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40999. }
  41000. if (defines.MORPHTARGETS) {
  41001. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41002. }
  41003. //Attributes
  41004. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41005. if (defines.NORMAL) {
  41006. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41007. }
  41008. if (defines.TANGENT) {
  41009. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41010. }
  41011. if (defines.UV1) {
  41012. attribs.push(BABYLON.VertexBuffer.UVKind);
  41013. }
  41014. if (defines.UV2) {
  41015. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41016. }
  41017. if (defines.VERTEXCOLOR) {
  41018. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41019. }
  41020. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41021. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41022. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41023. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41024. "vFogInfos", "vFogColor", "pointSize",
  41025. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41026. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41027. "mBones",
  41028. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41029. "vLightingIntensity",
  41030. "logarithmicDepthConstant",
  41031. "vSphericalX", "vSphericalY", "vSphericalZ",
  41032. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41033. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41034. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41035. "vTangentSpaceParams"
  41036. ];
  41037. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41038. "bumpSampler", "lightmapSampler", "opacitySampler",
  41039. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41040. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41041. "microSurfaceSampler", "environmentBrdfSampler"];
  41042. var uniformBuffers = ["Material", "Scene"];
  41043. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41044. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41045. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41046. uniformsNames: uniforms,
  41047. uniformBuffersNames: uniformBuffers,
  41048. samplers: samplers,
  41049. defines: defines,
  41050. maxSimultaneousLights: this._maxSimultaneousLights
  41051. });
  41052. var join = defines.toString();
  41053. return engine.createEffect("pbr", {
  41054. attributes: attribs,
  41055. uniformsNames: uniforms,
  41056. uniformBuffersNames: uniformBuffers,
  41057. samplers: samplers,
  41058. defines: join,
  41059. fallbacks: fallbacks,
  41060. onCompiled: onCompiled,
  41061. onError: onError,
  41062. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41063. }, engine);
  41064. };
  41065. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41066. if (useInstances === void 0) { useInstances = null; }
  41067. if (useClipPlane === void 0) { useClipPlane = null; }
  41068. var scene = this.getScene();
  41069. var engine = scene.getEngine();
  41070. // Lights
  41071. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41072. defines._needNormals = true;
  41073. // Textures
  41074. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41075. if (defines._areTexturesDirty) {
  41076. defines._needUVs = false;
  41077. if (scene.texturesEnabled) {
  41078. if (scene.getEngine().getCaps().textureLOD) {
  41079. defines.LODBASEDMICROSFURACE = true;
  41080. }
  41081. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41082. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41083. }
  41084. else {
  41085. defines.ALBEDO = false;
  41086. }
  41087. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41088. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41089. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41090. }
  41091. else {
  41092. defines.AMBIENT = false;
  41093. }
  41094. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41095. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41096. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41097. }
  41098. else {
  41099. defines.OPACITY = false;
  41100. }
  41101. var reflectionTexture = this._getReflectionTexture();
  41102. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41103. defines.REFLECTION = true;
  41104. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41105. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41106. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41107. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41108. defines.INVERTCUBICMAP = true;
  41109. }
  41110. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41111. switch (reflectionTexture.coordinatesMode) {
  41112. case BABYLON.Texture.CUBIC_MODE:
  41113. case BABYLON.Texture.INVCUBIC_MODE:
  41114. defines.REFLECTIONMAP_CUBIC = true;
  41115. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41116. break;
  41117. case BABYLON.Texture.EXPLICIT_MODE:
  41118. defines.REFLECTIONMAP_EXPLICIT = true;
  41119. break;
  41120. case BABYLON.Texture.PLANAR_MODE:
  41121. defines.REFLECTIONMAP_PLANAR = true;
  41122. break;
  41123. case BABYLON.Texture.PROJECTION_MODE:
  41124. defines.REFLECTIONMAP_PROJECTION = true;
  41125. break;
  41126. case BABYLON.Texture.SKYBOX_MODE:
  41127. defines.REFLECTIONMAP_SKYBOX = true;
  41128. break;
  41129. case BABYLON.Texture.SPHERICAL_MODE:
  41130. defines.REFLECTIONMAP_SPHERICAL = true;
  41131. break;
  41132. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41133. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41134. break;
  41135. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41136. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41137. break;
  41138. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41139. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41140. break;
  41141. }
  41142. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41143. if (reflectionTexture.sphericalPolynomial) {
  41144. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41145. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41146. defines.USESPHERICALINVERTEX = false;
  41147. }
  41148. else {
  41149. defines.USESPHERICALINVERTEX = true;
  41150. }
  41151. }
  41152. }
  41153. }
  41154. else {
  41155. defines.REFLECTION = false;
  41156. defines.REFLECTIONMAP_3D = false;
  41157. defines.REFLECTIONMAP_SPHERICAL = false;
  41158. defines.REFLECTIONMAP_PLANAR = false;
  41159. defines.REFLECTIONMAP_CUBIC = false;
  41160. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41161. defines.REFLECTIONMAP_PROJECTION = false;
  41162. defines.REFLECTIONMAP_SKYBOX = false;
  41163. defines.REFLECTIONMAP_EXPLICIT = false;
  41164. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41165. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41166. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41167. defines.INVERTCUBICMAP = false;
  41168. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41169. defines.USESPHERICALINVERTEX = false;
  41170. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41171. defines.LODINREFLECTIONALPHA = false;
  41172. defines.GAMMAREFLECTION = false;
  41173. }
  41174. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41175. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41176. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41177. }
  41178. else {
  41179. defines.LIGHTMAP = false;
  41180. }
  41181. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41182. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41183. }
  41184. else {
  41185. defines.EMISSIVE = false;
  41186. }
  41187. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41188. if (this._metallicTexture) {
  41189. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41190. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41191. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41192. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41193. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41194. }
  41195. else if (this._reflectivityTexture) {
  41196. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41197. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41198. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41199. }
  41200. else {
  41201. defines.REFLECTIVITY = false;
  41202. }
  41203. if (this._microSurfaceTexture) {
  41204. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41205. }
  41206. else {
  41207. defines.MICROSURFACEMAP = false;
  41208. }
  41209. }
  41210. else {
  41211. defines.REFLECTIVITY = false;
  41212. defines.MICROSURFACEMAP = false;
  41213. }
  41214. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41215. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41216. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41217. defines.PARALLAX = true;
  41218. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41219. }
  41220. else {
  41221. defines.PARALLAX = false;
  41222. }
  41223. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41224. }
  41225. else {
  41226. defines.BUMP = false;
  41227. }
  41228. var refractionTexture = this._getRefractionTexture();
  41229. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41230. defines.REFRACTION = true;
  41231. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41232. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41233. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41234. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41235. if (this._linkRefractionWithTransparency) {
  41236. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41237. }
  41238. }
  41239. else {
  41240. defines.REFRACTION = false;
  41241. }
  41242. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41243. defines.ENVIRONMENTBRDF = true;
  41244. }
  41245. else {
  41246. defines.ENVIRONMENTBRDF = false;
  41247. }
  41248. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41249. defines.ALPHAFROMALBEDO = true;
  41250. }
  41251. else {
  41252. defines.ALPHAFROMALBEDO = false;
  41253. }
  41254. }
  41255. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41256. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41257. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41258. if (!this.backFaceCulling && this._twoSidedLighting) {
  41259. defines.TWOSIDEDLIGHTING = true;
  41260. }
  41261. else {
  41262. defines.TWOSIDEDLIGHTING = false;
  41263. }
  41264. defines.ALPHATESTVALUE = this._alphaCutOff;
  41265. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41266. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41267. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41268. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41269. }
  41270. if (defines._areImageProcessingDirty) {
  41271. this._imageProcessingConfiguration.prepareDefines(defines);
  41272. }
  41273. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41274. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41275. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41276. // Misc.
  41277. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41278. // Values that need to be evaluated on every frame
  41279. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41280. // Attribs
  41281. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41282. };
  41283. /**
  41284. * Force shader compilation
  41285. */
  41286. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41287. var _this = this;
  41288. var localOptions = __assign({ clipPlane: false }, options);
  41289. var defines = new PBRMaterialDefines();
  41290. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41291. if (effect.isReady()) {
  41292. if (onCompiled) {
  41293. onCompiled(this);
  41294. }
  41295. }
  41296. else {
  41297. effect.onCompileObservable.add(function () {
  41298. if (onCompiled) {
  41299. onCompiled(_this);
  41300. }
  41301. });
  41302. }
  41303. };
  41304. /**
  41305. * Initializes the uniform buffer layout for the shader.
  41306. */
  41307. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41308. // Order is important !
  41309. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41310. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41311. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41312. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41313. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41314. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41315. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41316. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41317. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41318. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41319. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41320. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41321. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41322. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41323. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41324. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41325. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41326. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41327. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41328. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41329. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41330. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41331. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41332. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41333. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41334. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41335. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41336. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41337. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41338. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41339. this._uniformBuffer.addUniform("pointSize", 1);
  41340. this._uniformBuffer.create();
  41341. };
  41342. /**
  41343. * Unbinds the textures.
  41344. */
  41345. PBRBaseMaterial.prototype.unbind = function () {
  41346. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41347. this._uniformBuffer.setTexture("reflectionSampler", null);
  41348. }
  41349. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41350. this._uniformBuffer.setTexture("refractionSampler", null);
  41351. }
  41352. _super.prototype.unbind.call(this);
  41353. };
  41354. /**
  41355. * Binds the submesh data.
  41356. * @param world - The world matrix.
  41357. * @param mesh - The BJS mesh.
  41358. * @param subMesh - A submesh of the BJS mesh.
  41359. */
  41360. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41361. var scene = this.getScene();
  41362. var defines = subMesh._materialDefines;
  41363. if (!defines) {
  41364. return;
  41365. }
  41366. var effect = subMesh.effect;
  41367. if (!effect) {
  41368. return;
  41369. }
  41370. this._activeEffect = effect;
  41371. // Matrices
  41372. this.bindOnlyWorldMatrix(world);
  41373. // Normal Matrix
  41374. if (defines.OBJECTSPACE_NORMALMAP) {
  41375. world.toNormalMatrix(this._normalMatrix);
  41376. this.bindOnlyNormalMatrix(this._normalMatrix);
  41377. }
  41378. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41379. // Bones
  41380. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41381. var reflectionTexture = null;
  41382. if (mustRebind) {
  41383. this._uniformBuffer.bindToEffect(effect, "Material");
  41384. this.bindViewProjection(effect);
  41385. reflectionTexture = this._getReflectionTexture();
  41386. var refractionTexture = this._getRefractionTexture();
  41387. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41388. // Texture uniforms
  41389. if (scene.texturesEnabled) {
  41390. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41391. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41392. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41393. }
  41394. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41395. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41396. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41397. }
  41398. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41399. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41400. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41401. }
  41402. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41403. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41404. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41405. if (reflectionTexture.boundingBoxSize) {
  41406. var cubeTexture = reflectionTexture;
  41407. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41408. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41409. }
  41410. var polynomials = reflectionTexture.sphericalPolynomial;
  41411. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41412. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41413. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41414. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41415. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41416. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41417. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41418. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41419. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41420. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41421. }
  41422. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41423. }
  41424. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41425. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41426. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41427. }
  41428. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41429. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41430. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41431. }
  41432. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41433. if (this._metallicTexture) {
  41434. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41435. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41436. }
  41437. else if (this._reflectivityTexture) {
  41438. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41439. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41440. }
  41441. if (this._microSurfaceTexture) {
  41442. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41443. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41444. }
  41445. }
  41446. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41447. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41448. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41449. if (scene._mirroredCameraPosition) {
  41450. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41451. }
  41452. else {
  41453. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41454. }
  41455. }
  41456. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41457. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41458. var depth = 1.0;
  41459. if (!refractionTexture.isCube) {
  41460. if (refractionTexture.depth) {
  41461. depth = refractionTexture.depth;
  41462. }
  41463. }
  41464. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41465. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41466. }
  41467. }
  41468. // Point size
  41469. if (this.pointsCloud) {
  41470. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41471. }
  41472. // Colors
  41473. if (defines.METALLICWORKFLOW) {
  41474. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41475. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41476. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41477. }
  41478. else {
  41479. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41480. }
  41481. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41482. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41483. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41484. // Misc
  41485. this._lightingInfos.x = this._directIntensity;
  41486. this._lightingInfos.y = this._emissiveIntensity;
  41487. this._lightingInfos.z = this._environmentIntensity;
  41488. this._lightingInfos.w = this._specularIntensity;
  41489. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41490. }
  41491. // Textures
  41492. if (scene.texturesEnabled) {
  41493. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41494. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41495. }
  41496. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41497. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41498. }
  41499. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41500. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41501. }
  41502. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41503. if (defines.LODBASEDMICROSFURACE) {
  41504. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41505. }
  41506. else {
  41507. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41508. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41509. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41510. }
  41511. }
  41512. if (defines.ENVIRONMENTBRDF) {
  41513. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41514. }
  41515. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41516. if (defines.LODBASEDMICROSFURACE) {
  41517. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41518. }
  41519. else {
  41520. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41521. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41522. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41523. }
  41524. }
  41525. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41526. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41527. }
  41528. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41529. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41530. }
  41531. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41532. if (this._metallicTexture) {
  41533. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41534. }
  41535. else if (this._reflectivityTexture) {
  41536. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41537. }
  41538. if (this._microSurfaceTexture) {
  41539. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41540. }
  41541. }
  41542. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41543. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41544. }
  41545. }
  41546. // Clip plane
  41547. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41548. // Colors
  41549. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41550. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41551. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41552. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41553. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41554. }
  41555. if (mustRebind || !this.isFrozen) {
  41556. // Lights
  41557. if (scene.lightsEnabled && !this._disableLighting) {
  41558. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41559. }
  41560. // View
  41561. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41562. this.bindView(effect);
  41563. }
  41564. // Fog
  41565. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41566. // Morph targets
  41567. if (defines.NUM_MORPH_INFLUENCERS) {
  41568. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41569. }
  41570. // image processing
  41571. this._imageProcessingConfiguration.bind(this._activeEffect);
  41572. // Log. depth
  41573. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41574. }
  41575. this._uniformBuffer.update();
  41576. this._afterBind(mesh);
  41577. };
  41578. /**
  41579. * Returns the animatable textures.
  41580. * @returns - Array of animatable textures.
  41581. */
  41582. PBRBaseMaterial.prototype.getAnimatables = function () {
  41583. var results = [];
  41584. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41585. results.push(this._albedoTexture);
  41586. }
  41587. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41588. results.push(this._ambientTexture);
  41589. }
  41590. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41591. results.push(this._opacityTexture);
  41592. }
  41593. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41594. results.push(this._reflectionTexture);
  41595. }
  41596. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41597. results.push(this._emissiveTexture);
  41598. }
  41599. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41600. results.push(this._metallicTexture);
  41601. }
  41602. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41603. results.push(this._reflectivityTexture);
  41604. }
  41605. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41606. results.push(this._bumpTexture);
  41607. }
  41608. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41609. results.push(this._lightmapTexture);
  41610. }
  41611. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41612. results.push(this._refractionTexture);
  41613. }
  41614. return results;
  41615. };
  41616. /**
  41617. * Returns the texture used for reflections.
  41618. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41619. */
  41620. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41621. if (this._reflectionTexture) {
  41622. return this._reflectionTexture;
  41623. }
  41624. return this.getScene().environmentTexture;
  41625. };
  41626. /**
  41627. * Returns the texture used for refraction or null if none is used.
  41628. * @returns - Refection texture if present. If no refraction texture and refraction
  41629. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41630. */
  41631. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41632. if (this._refractionTexture) {
  41633. return this._refractionTexture;
  41634. }
  41635. if (this._linkRefractionWithTransparency) {
  41636. return this.getScene().environmentTexture;
  41637. }
  41638. return null;
  41639. };
  41640. /**
  41641. * Disposes the resources of the material.
  41642. * @param forceDisposeEffect - Forces the disposal of effects.
  41643. * @param forceDisposeTextures - Forces the disposal of all textures.
  41644. */
  41645. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41646. if (forceDisposeTextures) {
  41647. if (this._albedoTexture) {
  41648. this._albedoTexture.dispose();
  41649. }
  41650. if (this._ambientTexture) {
  41651. this._ambientTexture.dispose();
  41652. }
  41653. if (this._opacityTexture) {
  41654. this._opacityTexture.dispose();
  41655. }
  41656. if (this._reflectionTexture) {
  41657. this._reflectionTexture.dispose();
  41658. }
  41659. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41660. this._environmentBRDFTexture.dispose();
  41661. }
  41662. if (this._emissiveTexture) {
  41663. this._emissiveTexture.dispose();
  41664. }
  41665. if (this._metallicTexture) {
  41666. this._metallicTexture.dispose();
  41667. }
  41668. if (this._reflectivityTexture) {
  41669. this._reflectivityTexture.dispose();
  41670. }
  41671. if (this._bumpTexture) {
  41672. this._bumpTexture.dispose();
  41673. }
  41674. if (this._lightmapTexture) {
  41675. this._lightmapTexture.dispose();
  41676. }
  41677. if (this._refractionTexture) {
  41678. this._refractionTexture.dispose();
  41679. }
  41680. }
  41681. this._renderTargets.dispose();
  41682. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41683. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41684. }
  41685. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41686. };
  41687. /**
  41688. * Stores the reflectivity values based on metallic roughness workflow.
  41689. */
  41690. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41691. __decorate([
  41692. BABYLON.serializeAsImageProcessingConfiguration()
  41693. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41694. __decorate([
  41695. BABYLON.serialize()
  41696. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41697. __decorate([
  41698. BABYLON.serialize()
  41699. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41700. return PBRBaseMaterial;
  41701. }(BABYLON.PushMaterial));
  41702. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41703. })(BABYLON || (BABYLON = {}));
  41704. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41705. var BABYLON;
  41706. (function (BABYLON) {
  41707. /**
  41708. * The Physically based simple base material of BJS.
  41709. *
  41710. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41711. * It is used as the base class for both the specGloss and metalRough conventions.
  41712. */
  41713. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41714. __extends(PBRBaseSimpleMaterial, _super);
  41715. /**
  41716. * Instantiates a new PBRMaterial instance.
  41717. *
  41718. * @param name The material name
  41719. * @param scene The scene the material will be use in.
  41720. */
  41721. function PBRBaseSimpleMaterial(name, scene) {
  41722. var _this = _super.call(this, name, scene) || this;
  41723. /**
  41724. * Number of Simultaneous lights allowed on the material.
  41725. */
  41726. _this.maxSimultaneousLights = 4;
  41727. /**
  41728. * If sets to true, disables all the lights affecting the material.
  41729. */
  41730. _this.disableLighting = false;
  41731. /**
  41732. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41733. */
  41734. _this.invertNormalMapX = false;
  41735. /**
  41736. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41737. */
  41738. _this.invertNormalMapY = false;
  41739. /**
  41740. * Emissivie color used to self-illuminate the model.
  41741. */
  41742. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41743. /**
  41744. * Occlusion Channel Strenght.
  41745. */
  41746. _this.occlusionStrength = 1.0;
  41747. _this.useLightmapAsShadowmap = false;
  41748. _this._useAlphaFromAlbedoTexture = true;
  41749. _this._useAmbientInGrayScale = true;
  41750. return _this;
  41751. }
  41752. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41753. /**
  41754. * Gets the current double sided mode.
  41755. */
  41756. get: function () {
  41757. return this._twoSidedLighting;
  41758. },
  41759. /**
  41760. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41761. */
  41762. set: function (value) {
  41763. if (this._twoSidedLighting === value) {
  41764. return;
  41765. }
  41766. this._twoSidedLighting = value;
  41767. this.backFaceCulling = !value;
  41768. this._markAllSubMeshesAsTexturesDirty();
  41769. },
  41770. enumerable: true,
  41771. configurable: true
  41772. });
  41773. /**
  41774. * Return the active textures of the material.
  41775. */
  41776. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41777. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41778. if (this.environmentTexture) {
  41779. activeTextures.push(this.environmentTexture);
  41780. }
  41781. if (this.normalTexture) {
  41782. activeTextures.push(this.normalTexture);
  41783. }
  41784. if (this.emissiveTexture) {
  41785. activeTextures.push(this.emissiveTexture);
  41786. }
  41787. if (this.occlusionTexture) {
  41788. activeTextures.push(this.occlusionTexture);
  41789. }
  41790. if (this.lightmapTexture) {
  41791. activeTextures.push(this.lightmapTexture);
  41792. }
  41793. return activeTextures;
  41794. };
  41795. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41796. if (_super.prototype.hasTexture.call(this, texture)) {
  41797. return true;
  41798. }
  41799. if (this.lightmapTexture === texture) {
  41800. return true;
  41801. }
  41802. return false;
  41803. };
  41804. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41805. return "PBRBaseSimpleMaterial";
  41806. };
  41807. __decorate([
  41808. BABYLON.serialize(),
  41809. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41810. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41811. __decorate([
  41812. BABYLON.serialize(),
  41813. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41814. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41815. __decorate([
  41816. BABYLON.serializeAsTexture(),
  41817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41818. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41819. __decorate([
  41820. BABYLON.serialize(),
  41821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41822. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41823. __decorate([
  41824. BABYLON.serialize(),
  41825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41826. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41827. __decorate([
  41828. BABYLON.serializeAsTexture(),
  41829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41830. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41831. __decorate([
  41832. BABYLON.serializeAsColor3("emissive"),
  41833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41834. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41835. __decorate([
  41836. BABYLON.serializeAsTexture(),
  41837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41838. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41839. __decorate([
  41840. BABYLON.serialize(),
  41841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41842. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41843. __decorate([
  41844. BABYLON.serializeAsTexture(),
  41845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41846. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41847. __decorate([
  41848. BABYLON.serialize(),
  41849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41850. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41851. __decorate([
  41852. BABYLON.serialize()
  41853. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41854. __decorate([
  41855. BABYLON.serializeAsTexture(),
  41856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41857. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41858. __decorate([
  41859. BABYLON.serialize(),
  41860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41861. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41862. return PBRBaseSimpleMaterial;
  41863. }(BABYLON.PBRBaseMaterial));
  41864. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41865. })(BABYLON || (BABYLON = {}));
  41866. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41867. var BABYLON;
  41868. (function (BABYLON) {
  41869. /**
  41870. * The Physically based material of BJS.
  41871. *
  41872. * This offers the main features of a standard PBR material.
  41873. * For more information, please refer to the documentation :
  41874. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41875. */
  41876. var PBRMaterial = /** @class */ (function (_super) {
  41877. __extends(PBRMaterial, _super);
  41878. /**
  41879. * Instantiates a new PBRMaterial instance.
  41880. *
  41881. * @param name The material name
  41882. * @param scene The scene the material will be use in.
  41883. */
  41884. function PBRMaterial(name, scene) {
  41885. var _this = _super.call(this, name, scene) || this;
  41886. /**
  41887. * Intensity of the direct lights e.g. the four lights available in your scene.
  41888. * This impacts both the direct diffuse and specular highlights.
  41889. */
  41890. _this.directIntensity = 1.0;
  41891. /**
  41892. * Intensity of the emissive part of the material.
  41893. * This helps controlling the emissive effect without modifying the emissive color.
  41894. */
  41895. _this.emissiveIntensity = 1.0;
  41896. /**
  41897. * Intensity of the environment e.g. how much the environment will light the object
  41898. * either through harmonics for rough material or through the refelction for shiny ones.
  41899. */
  41900. _this.environmentIntensity = 1.0;
  41901. /**
  41902. * This is a special control allowing the reduction of the specular highlights coming from the
  41903. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41904. */
  41905. _this.specularIntensity = 1.0;
  41906. /**
  41907. * Debug Control allowing disabling the bump map on this material.
  41908. */
  41909. _this.disableBumpMap = false;
  41910. /**
  41911. * AKA Occlusion Texture Intensity in other nomenclature.
  41912. */
  41913. _this.ambientTextureStrength = 1.0;
  41914. /**
  41915. * The color of a material in ambient lighting.
  41916. */
  41917. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41918. /**
  41919. * AKA Diffuse Color in other nomenclature.
  41920. */
  41921. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41922. /**
  41923. * AKA Specular Color in other nomenclature.
  41924. */
  41925. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41926. /**
  41927. * The color reflected from the material.
  41928. */
  41929. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41930. /**
  41931. * The color emitted from the material.
  41932. */
  41933. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41934. /**
  41935. * AKA Glossiness in other nomenclature.
  41936. */
  41937. _this.microSurface = 1.0;
  41938. /**
  41939. * source material index of refraction (IOR)' / 'destination material IOR.
  41940. */
  41941. _this.indexOfRefraction = 0.66;
  41942. /**
  41943. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41944. */
  41945. _this.invertRefractionY = false;
  41946. /**
  41947. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41948. * Materials half opaque for instance using refraction could benefit from this control.
  41949. */
  41950. _this.linkRefractionWithTransparency = false;
  41951. _this.useLightmapAsShadowmap = false;
  41952. /**
  41953. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41954. */
  41955. _this.useAlphaFromAlbedoTexture = false;
  41956. /**
  41957. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41958. */
  41959. _this.forceAlphaTest = false;
  41960. /**
  41961. * Defines the alpha limits in alpha test mode.
  41962. */
  41963. _this.alphaCutOff = 0.4;
  41964. /**
  41965. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41966. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41967. */
  41968. _this.useSpecularOverAlpha = true;
  41969. /**
  41970. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41971. */
  41972. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41973. /**
  41974. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41975. */
  41976. _this.useRoughnessFromMetallicTextureAlpha = true;
  41977. /**
  41978. * Specifies if the metallic texture contains the roughness information in its green channel.
  41979. */
  41980. _this.useRoughnessFromMetallicTextureGreen = false;
  41981. /**
  41982. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41983. */
  41984. _this.useMetallnessFromMetallicTextureBlue = false;
  41985. /**
  41986. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41987. */
  41988. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41989. /**
  41990. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41991. */
  41992. _this.useAmbientInGrayScale = false;
  41993. /**
  41994. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41995. * The material will try to infer what glossiness each pixel should be.
  41996. */
  41997. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41998. /**
  41999. * BJS is using an harcoded light falloff based on a manually sets up range.
  42000. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42001. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42002. */
  42003. _this.usePhysicalLightFalloff = true;
  42004. /**
  42005. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42006. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42007. */
  42008. _this.useRadianceOverAlpha = true;
  42009. /**
  42010. * Allows using an object space normal map (instead of tangent space).
  42011. */
  42012. _this.useObjectSpaceNormalMap = false;
  42013. /**
  42014. * Allows using the bump map in parallax mode.
  42015. */
  42016. _this.useParallax = false;
  42017. /**
  42018. * Allows using the bump map in parallax occlusion mode.
  42019. */
  42020. _this.useParallaxOcclusion = false;
  42021. /**
  42022. * Controls the scale bias of the parallax mode.
  42023. */
  42024. _this.parallaxScaleBias = 0.05;
  42025. /**
  42026. * If sets to true, disables all the lights affecting the material.
  42027. */
  42028. _this.disableLighting = false;
  42029. /**
  42030. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42031. */
  42032. _this.forceIrradianceInFragment = false;
  42033. /**
  42034. * Number of Simultaneous lights allowed on the material.
  42035. */
  42036. _this.maxSimultaneousLights = 4;
  42037. /**
  42038. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42039. */
  42040. _this.invertNormalMapX = false;
  42041. /**
  42042. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42043. */
  42044. _this.invertNormalMapY = false;
  42045. /**
  42046. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42047. */
  42048. _this.twoSidedLighting = false;
  42049. /**
  42050. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42051. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42052. */
  42053. _this.useAlphaFresnel = false;
  42054. /**
  42055. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42056. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42057. */
  42058. _this.useLinearAlphaFresnel = false;
  42059. /**
  42060. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42061. * And/Or occlude the blended part.
  42062. */
  42063. _this.environmentBRDFTexture = null;
  42064. /**
  42065. * Force normal to face away from face.
  42066. */
  42067. _this.forceNormalForward = false;
  42068. /**
  42069. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42070. * makes the reflect vector face the model (under horizon).
  42071. */
  42072. _this.useHorizonOcclusion = true;
  42073. /**
  42074. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42075. * too much the area relying on ambient texture to define their ambient occlusion.
  42076. */
  42077. _this.useRadianceOcclusion = true;
  42078. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42079. return _this;
  42080. }
  42081. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42082. /**
  42083. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42084. */
  42085. get: function () {
  42086. return this._PBRMATERIAL_OPAQUE;
  42087. },
  42088. enumerable: true,
  42089. configurable: true
  42090. });
  42091. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42092. /**
  42093. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42094. */
  42095. get: function () {
  42096. return this._PBRMATERIAL_ALPHATEST;
  42097. },
  42098. enumerable: true,
  42099. configurable: true
  42100. });
  42101. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42102. /**
  42103. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42104. */
  42105. get: function () {
  42106. return this._PBRMATERIAL_ALPHABLEND;
  42107. },
  42108. enumerable: true,
  42109. configurable: true
  42110. });
  42111. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42112. /**
  42113. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42114. * They are also discarded below the alpha cutoff threshold to improve performances.
  42115. */
  42116. get: function () {
  42117. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42118. },
  42119. enumerable: true,
  42120. configurable: true
  42121. });
  42122. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42123. /**
  42124. * Gets the image processing configuration used either in this material.
  42125. */
  42126. get: function () {
  42127. return this._imageProcessingConfiguration;
  42128. },
  42129. /**
  42130. * Sets the Default image processing configuration used either in the this material.
  42131. *
  42132. * If sets to null, the scene one is in use.
  42133. */
  42134. set: function (value) {
  42135. this._attachImageProcessingConfiguration(value);
  42136. // Ensure the effect will be rebuilt.
  42137. this._markAllSubMeshesAsTexturesDirty();
  42138. },
  42139. enumerable: true,
  42140. configurable: true
  42141. });
  42142. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42143. /**
  42144. * Gets wether the color curves effect is enabled.
  42145. */
  42146. get: function () {
  42147. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42148. },
  42149. /**
  42150. * Sets wether the color curves effect is enabled.
  42151. */
  42152. set: function (value) {
  42153. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42154. },
  42155. enumerable: true,
  42156. configurable: true
  42157. });
  42158. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42159. /**
  42160. * Gets wether the color grading effect is enabled.
  42161. */
  42162. get: function () {
  42163. return this.imageProcessingConfiguration.colorGradingEnabled;
  42164. },
  42165. /**
  42166. * Gets wether the color grading effect is enabled.
  42167. */
  42168. set: function (value) {
  42169. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42170. },
  42171. enumerable: true,
  42172. configurable: true
  42173. });
  42174. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42175. /**
  42176. * Gets wether tonemapping is enabled or not.
  42177. */
  42178. get: function () {
  42179. return this._imageProcessingConfiguration.toneMappingEnabled;
  42180. },
  42181. /**
  42182. * Sets wether tonemapping is enabled or not
  42183. */
  42184. set: function (value) {
  42185. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42186. },
  42187. enumerable: true,
  42188. configurable: true
  42189. });
  42190. ;
  42191. ;
  42192. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42193. /**
  42194. * The camera exposure used on this material.
  42195. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42196. * This corresponds to a photographic exposure.
  42197. */
  42198. get: function () {
  42199. return this._imageProcessingConfiguration.exposure;
  42200. },
  42201. /**
  42202. * The camera exposure used on this material.
  42203. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42204. * This corresponds to a photographic exposure.
  42205. */
  42206. set: function (value) {
  42207. this._imageProcessingConfiguration.exposure = value;
  42208. },
  42209. enumerable: true,
  42210. configurable: true
  42211. });
  42212. ;
  42213. ;
  42214. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42215. /**
  42216. * Gets The camera contrast used on this material.
  42217. */
  42218. get: function () {
  42219. return this._imageProcessingConfiguration.contrast;
  42220. },
  42221. /**
  42222. * Sets The camera contrast used on this material.
  42223. */
  42224. set: function (value) {
  42225. this._imageProcessingConfiguration.contrast = value;
  42226. },
  42227. enumerable: true,
  42228. configurable: true
  42229. });
  42230. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42231. /**
  42232. * Gets the Color Grading 2D Lookup Texture.
  42233. */
  42234. get: function () {
  42235. return this._imageProcessingConfiguration.colorGradingTexture;
  42236. },
  42237. /**
  42238. * Sets the Color Grading 2D Lookup Texture.
  42239. */
  42240. set: function (value) {
  42241. this._imageProcessingConfiguration.colorGradingTexture = value;
  42242. },
  42243. enumerable: true,
  42244. configurable: true
  42245. });
  42246. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42247. /**
  42248. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42249. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42250. * 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;
  42251. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42252. */
  42253. get: function () {
  42254. return this._imageProcessingConfiguration.colorCurves;
  42255. },
  42256. /**
  42257. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42258. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42259. * 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;
  42260. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42261. */
  42262. set: function (value) {
  42263. this._imageProcessingConfiguration.colorCurves = value;
  42264. },
  42265. enumerable: true,
  42266. configurable: true
  42267. });
  42268. /**
  42269. * Returns the name of this material class.
  42270. */
  42271. PBRMaterial.prototype.getClassName = function () {
  42272. return "PBRMaterial";
  42273. };
  42274. /**
  42275. * Returns an array of the actively used textures.
  42276. * @returns - Array of BaseTextures
  42277. */
  42278. PBRMaterial.prototype.getActiveTextures = function () {
  42279. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42280. if (this._albedoTexture) {
  42281. activeTextures.push(this._albedoTexture);
  42282. }
  42283. if (this._ambientTexture) {
  42284. activeTextures.push(this._ambientTexture);
  42285. }
  42286. if (this._opacityTexture) {
  42287. activeTextures.push(this._opacityTexture);
  42288. }
  42289. if (this._reflectionTexture) {
  42290. activeTextures.push(this._reflectionTexture);
  42291. }
  42292. if (this._emissiveTexture) {
  42293. activeTextures.push(this._emissiveTexture);
  42294. }
  42295. if (this._reflectivityTexture) {
  42296. activeTextures.push(this._reflectivityTexture);
  42297. }
  42298. if (this._metallicTexture) {
  42299. activeTextures.push(this._metallicTexture);
  42300. }
  42301. if (this._microSurfaceTexture) {
  42302. activeTextures.push(this._microSurfaceTexture);
  42303. }
  42304. if (this._bumpTexture) {
  42305. activeTextures.push(this._bumpTexture);
  42306. }
  42307. if (this._lightmapTexture) {
  42308. activeTextures.push(this._lightmapTexture);
  42309. }
  42310. if (this._refractionTexture) {
  42311. activeTextures.push(this._refractionTexture);
  42312. }
  42313. return activeTextures;
  42314. };
  42315. /**
  42316. * Checks to see if a texture is used in the material.
  42317. * @param texture - Base texture to use.
  42318. * @returns - Boolean specifying if a texture is used in the material.
  42319. */
  42320. PBRMaterial.prototype.hasTexture = function (texture) {
  42321. if (_super.prototype.hasTexture.call(this, texture)) {
  42322. return true;
  42323. }
  42324. if (this._albedoTexture === texture) {
  42325. return true;
  42326. }
  42327. if (this._ambientTexture === texture) {
  42328. return true;
  42329. }
  42330. if (this._opacityTexture === texture) {
  42331. return true;
  42332. }
  42333. if (this._reflectionTexture === texture) {
  42334. return true;
  42335. }
  42336. if (this._reflectivityTexture === texture) {
  42337. return true;
  42338. }
  42339. if (this._metallicTexture === texture) {
  42340. return true;
  42341. }
  42342. if (this._microSurfaceTexture === texture) {
  42343. return true;
  42344. }
  42345. if (this._bumpTexture === texture) {
  42346. return true;
  42347. }
  42348. if (this._lightmapTexture === texture) {
  42349. return true;
  42350. }
  42351. if (this._refractionTexture === texture) {
  42352. return true;
  42353. }
  42354. return false;
  42355. };
  42356. /**
  42357. * Makes a duplicate of the current material.
  42358. * @param name - name to use for the new material.
  42359. */
  42360. PBRMaterial.prototype.clone = function (name) {
  42361. var _this = this;
  42362. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42363. clone.id = name;
  42364. clone.name = name;
  42365. return clone;
  42366. };
  42367. /**
  42368. * Serializes this PBR Material.
  42369. * @returns - An object with the serialized material.
  42370. */
  42371. PBRMaterial.prototype.serialize = function () {
  42372. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42373. serializationObject.customType = "BABYLON.PBRMaterial";
  42374. return serializationObject;
  42375. };
  42376. // Statics
  42377. /**
  42378. * Parses a PBR Material from a serialized object.
  42379. * @param source - Serialized object.
  42380. * @param scene - BJS scene instance.
  42381. * @param rootUrl - url for the scene object
  42382. * @returns - PBRMaterial
  42383. */
  42384. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42385. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42386. };
  42387. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42388. /**
  42389. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42390. */
  42391. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42392. /**
  42393. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42394. */
  42395. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42396. /**
  42397. * 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.
  42398. * They are also discarded below the alpha cutoff threshold to improve performances.
  42399. */
  42400. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42401. __decorate([
  42402. BABYLON.serialize(),
  42403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42404. ], PBRMaterial.prototype, "directIntensity", void 0);
  42405. __decorate([
  42406. BABYLON.serialize(),
  42407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42408. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42409. __decorate([
  42410. BABYLON.serialize(),
  42411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42412. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42413. __decorate([
  42414. BABYLON.serialize(),
  42415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42416. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42417. __decorate([
  42418. BABYLON.serialize(),
  42419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42420. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42421. __decorate([
  42422. BABYLON.serializeAsTexture(),
  42423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42424. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42425. __decorate([
  42426. BABYLON.serializeAsTexture(),
  42427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42428. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42429. __decorate([
  42430. BABYLON.serialize(),
  42431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42432. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42433. __decorate([
  42434. BABYLON.serializeAsTexture(),
  42435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42436. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42437. __decorate([
  42438. BABYLON.serializeAsTexture(),
  42439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42440. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42441. __decorate([
  42442. BABYLON.serializeAsTexture(),
  42443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42444. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42445. __decorate([
  42446. BABYLON.serializeAsTexture(),
  42447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42448. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42449. __decorate([
  42450. BABYLON.serializeAsTexture(),
  42451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42452. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42453. __decorate([
  42454. BABYLON.serialize(),
  42455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42456. ], PBRMaterial.prototype, "metallic", void 0);
  42457. __decorate([
  42458. BABYLON.serialize(),
  42459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42460. ], PBRMaterial.prototype, "roughness", void 0);
  42461. __decorate([
  42462. BABYLON.serializeAsTexture(),
  42463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42464. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42465. __decorate([
  42466. BABYLON.serializeAsTexture(),
  42467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42468. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42469. __decorate([
  42470. BABYLON.serializeAsTexture(),
  42471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42472. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42473. __decorate([
  42474. BABYLON.serializeAsTexture(),
  42475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42476. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42477. __decorate([
  42478. BABYLON.serializeAsColor3("ambient"),
  42479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42480. ], PBRMaterial.prototype, "ambientColor", void 0);
  42481. __decorate([
  42482. BABYLON.serializeAsColor3("albedo"),
  42483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42484. ], PBRMaterial.prototype, "albedoColor", void 0);
  42485. __decorate([
  42486. BABYLON.serializeAsColor3("reflectivity"),
  42487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42488. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42489. __decorate([
  42490. BABYLON.serializeAsColor3("reflection"),
  42491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42492. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42493. __decorate([
  42494. BABYLON.serializeAsColor3("emissive"),
  42495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42496. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42497. __decorate([
  42498. BABYLON.serialize(),
  42499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42500. ], PBRMaterial.prototype, "microSurface", void 0);
  42501. __decorate([
  42502. BABYLON.serialize(),
  42503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42504. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42505. __decorate([
  42506. BABYLON.serialize(),
  42507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42508. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42509. __decorate([
  42510. BABYLON.serialize(),
  42511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42512. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42513. __decorate([
  42514. BABYLON.serialize(),
  42515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42516. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42517. __decorate([
  42518. BABYLON.serialize(),
  42519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42520. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42521. __decorate([
  42522. BABYLON.serialize(),
  42523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42524. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42525. __decorate([
  42526. BABYLON.serialize(),
  42527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42528. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42529. __decorate([
  42530. BABYLON.serialize(),
  42531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42532. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42533. __decorate([
  42534. BABYLON.serialize(),
  42535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42536. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42537. __decorate([
  42538. BABYLON.serialize(),
  42539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42540. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42541. __decorate([
  42542. BABYLON.serialize(),
  42543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42544. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42545. __decorate([
  42546. BABYLON.serialize(),
  42547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42548. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42549. __decorate([
  42550. BABYLON.serialize(),
  42551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42552. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42553. __decorate([
  42554. BABYLON.serialize(),
  42555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42556. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42557. __decorate([
  42558. BABYLON.serialize(),
  42559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42560. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42561. __decorate([
  42562. BABYLON.serialize(),
  42563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42564. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42565. __decorate([
  42566. BABYLON.serialize(),
  42567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42568. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42569. __decorate([
  42570. BABYLON.serialize(),
  42571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42572. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42573. __decorate([
  42574. BABYLON.serialize(),
  42575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42576. ], PBRMaterial.prototype, "useParallax", void 0);
  42577. __decorate([
  42578. BABYLON.serialize(),
  42579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42580. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42581. __decorate([
  42582. BABYLON.serialize(),
  42583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42584. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42585. __decorate([
  42586. BABYLON.serialize(),
  42587. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42588. ], PBRMaterial.prototype, "disableLighting", void 0);
  42589. __decorate([
  42590. BABYLON.serialize(),
  42591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42592. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42593. __decorate([
  42594. BABYLON.serialize(),
  42595. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42596. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42597. __decorate([
  42598. BABYLON.serialize(),
  42599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42600. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42601. __decorate([
  42602. BABYLON.serialize(),
  42603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42604. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42605. __decorate([
  42606. BABYLON.serialize(),
  42607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42608. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42609. __decorate([
  42610. BABYLON.serialize(),
  42611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42612. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42613. __decorate([
  42614. BABYLON.serialize(),
  42615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42616. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42617. __decorate([
  42618. BABYLON.serializeAsTexture(),
  42619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42620. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42621. __decorate([
  42622. BABYLON.serialize(),
  42623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42624. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42625. __decorate([
  42626. BABYLON.serialize(),
  42627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42628. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42629. __decorate([
  42630. BABYLON.serialize(),
  42631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42632. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42633. return PBRMaterial;
  42634. }(BABYLON.PBRBaseMaterial));
  42635. BABYLON.PBRMaterial = PBRMaterial;
  42636. })(BABYLON || (BABYLON = {}));
  42637. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42638. var BABYLON;
  42639. (function (BABYLON) {
  42640. /**
  42641. * The PBR material of BJS following the metal roughness convention.
  42642. *
  42643. * This fits to the PBR convention in the GLTF definition:
  42644. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42645. */
  42646. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42647. __extends(PBRMetallicRoughnessMaterial, _super);
  42648. /**
  42649. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42650. *
  42651. * @param name The material name
  42652. * @param scene The scene the material will be use in.
  42653. */
  42654. function PBRMetallicRoughnessMaterial(name, scene) {
  42655. var _this = _super.call(this, name, scene) || this;
  42656. _this._useRoughnessFromMetallicTextureAlpha = false;
  42657. _this._useRoughnessFromMetallicTextureGreen = true;
  42658. _this._useMetallnessFromMetallicTextureBlue = true;
  42659. _this.metallic = 1.0;
  42660. _this.roughness = 1.0;
  42661. return _this;
  42662. }
  42663. /**
  42664. * Return the currrent class name of the material.
  42665. */
  42666. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42667. return "PBRMetallicRoughnessMaterial";
  42668. };
  42669. /**
  42670. * Return the active textures of the material.
  42671. */
  42672. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42673. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42674. if (this.baseTexture) {
  42675. activeTextures.push(this.baseTexture);
  42676. }
  42677. if (this.metallicRoughnessTexture) {
  42678. activeTextures.push(this.metallicRoughnessTexture);
  42679. }
  42680. return activeTextures;
  42681. };
  42682. /**
  42683. * Checks to see if a texture is used in the material.
  42684. * @param texture - Base texture to use.
  42685. * @returns - Boolean specifying if a texture is used in the material.
  42686. */
  42687. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42688. if (_super.prototype.hasTexture.call(this, texture)) {
  42689. return true;
  42690. }
  42691. if (this.baseTexture === texture) {
  42692. return true;
  42693. }
  42694. if (this.metallicRoughnessTexture === texture) {
  42695. return true;
  42696. }
  42697. return false;
  42698. };
  42699. /**
  42700. * Makes a duplicate of the current material.
  42701. * @param name - name to use for the new material.
  42702. */
  42703. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42704. var _this = this;
  42705. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42706. clone.id = name;
  42707. clone.name = name;
  42708. return clone;
  42709. };
  42710. /**
  42711. * Serialize the material to a parsable JSON object.
  42712. */
  42713. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42714. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42715. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42716. return serializationObject;
  42717. };
  42718. /**
  42719. * Parses a JSON object correponding to the serialize function.
  42720. */
  42721. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42722. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42723. };
  42724. __decorate([
  42725. BABYLON.serializeAsColor3(),
  42726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42727. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42728. __decorate([
  42729. BABYLON.serializeAsTexture(),
  42730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42731. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42732. __decorate([
  42733. BABYLON.serialize(),
  42734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42735. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42736. __decorate([
  42737. BABYLON.serialize(),
  42738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42739. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42740. __decorate([
  42741. BABYLON.serializeAsTexture(),
  42742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42743. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42744. return PBRMetallicRoughnessMaterial;
  42745. }(BABYLON.PBRBaseSimpleMaterial));
  42746. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42747. })(BABYLON || (BABYLON = {}));
  42748. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42749. var BABYLON;
  42750. (function (BABYLON) {
  42751. /**
  42752. * The PBR material of BJS following the specular glossiness convention.
  42753. *
  42754. * This fits to the PBR convention in the GLTF definition:
  42755. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42756. */
  42757. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42758. __extends(PBRSpecularGlossinessMaterial, _super);
  42759. /**
  42760. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42761. *
  42762. * @param name The material name
  42763. * @param scene The scene the material will be use in.
  42764. */
  42765. function PBRSpecularGlossinessMaterial(name, scene) {
  42766. var _this = _super.call(this, name, scene) || this;
  42767. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42768. return _this;
  42769. }
  42770. /**
  42771. * Return the currrent class name of the material.
  42772. */
  42773. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42774. return "PBRSpecularGlossinessMaterial";
  42775. };
  42776. /**
  42777. * Return the active textures of the material.
  42778. */
  42779. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42780. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42781. if (this.diffuseTexture) {
  42782. activeTextures.push(this.diffuseTexture);
  42783. }
  42784. if (this.specularGlossinessTexture) {
  42785. activeTextures.push(this.specularGlossinessTexture);
  42786. }
  42787. return activeTextures;
  42788. };
  42789. /**
  42790. * Checks to see if a texture is used in the material.
  42791. * @param texture - Base texture to use.
  42792. * @returns - Boolean specifying if a texture is used in the material.
  42793. */
  42794. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42795. if (_super.prototype.hasTexture.call(this, texture)) {
  42796. return true;
  42797. }
  42798. if (this.diffuseTexture === texture) {
  42799. return true;
  42800. }
  42801. if (this.specularGlossinessTexture === texture) {
  42802. return true;
  42803. }
  42804. return false;
  42805. };
  42806. /**
  42807. * Makes a duplicate of the current material.
  42808. * @param name - name to use for the new material.
  42809. */
  42810. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42811. var _this = this;
  42812. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42813. clone.id = name;
  42814. clone.name = name;
  42815. return clone;
  42816. };
  42817. /**
  42818. * Serialize the material to a parsable JSON object.
  42819. */
  42820. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42821. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42822. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42823. return serializationObject;
  42824. };
  42825. /**
  42826. * Parses a JSON object correponding to the serialize function.
  42827. */
  42828. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42829. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42830. };
  42831. __decorate([
  42832. BABYLON.serializeAsColor3("diffuse"),
  42833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42834. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42835. __decorate([
  42836. BABYLON.serializeAsTexture(),
  42837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42838. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42839. __decorate([
  42840. BABYLON.serializeAsColor3("specular"),
  42841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42842. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42843. __decorate([
  42844. BABYLON.serialize(),
  42845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42846. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42847. __decorate([
  42848. BABYLON.serializeAsTexture(),
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42850. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42851. return PBRSpecularGlossinessMaterial;
  42852. }(BABYLON.PBRBaseSimpleMaterial));
  42853. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42854. })(BABYLON || (BABYLON = {}));
  42855. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42856. var BABYLON;
  42857. (function (BABYLON) {
  42858. BABYLON.CameraInputTypes = {};
  42859. var CameraInputsManager = /** @class */ (function () {
  42860. function CameraInputsManager(camera) {
  42861. this.attached = {};
  42862. this.camera = camera;
  42863. this.checkInputs = function () { };
  42864. }
  42865. /**
  42866. * Add an input method to a camera.
  42867. * builtin inputs example: camera.inputs.addGamepad();
  42868. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42869. * @param input camera input method
  42870. */
  42871. CameraInputsManager.prototype.add = function (input) {
  42872. var type = input.getSimpleName();
  42873. if (this.attached[type]) {
  42874. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42875. return;
  42876. }
  42877. this.attached[type] = input;
  42878. input.camera = this.camera;
  42879. //for checkInputs, we are dynamically creating a function
  42880. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42881. if (input.checkInputs) {
  42882. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42883. }
  42884. if (this.attachedElement) {
  42885. input.attachControl(this.attachedElement);
  42886. }
  42887. };
  42888. /**
  42889. * Remove a specific input method from a camera
  42890. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42891. * @param inputToRemove camera input method
  42892. */
  42893. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42894. for (var cam in this.attached) {
  42895. var input = this.attached[cam];
  42896. if (input === inputToRemove) {
  42897. input.detachControl(this.attachedElement);
  42898. input.camera = null;
  42899. delete this.attached[cam];
  42900. this.rebuildInputCheck();
  42901. }
  42902. }
  42903. };
  42904. CameraInputsManager.prototype.removeByType = function (inputType) {
  42905. for (var cam in this.attached) {
  42906. var input = this.attached[cam];
  42907. if (input.getClassName() === inputType) {
  42908. input.detachControl(this.attachedElement);
  42909. input.camera = null;
  42910. delete this.attached[cam];
  42911. this.rebuildInputCheck();
  42912. }
  42913. }
  42914. };
  42915. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42916. var current = this.checkInputs;
  42917. return function () {
  42918. current();
  42919. fn();
  42920. };
  42921. };
  42922. CameraInputsManager.prototype.attachInput = function (input) {
  42923. if (this.attachedElement) {
  42924. input.attachControl(this.attachedElement, this.noPreventDefault);
  42925. }
  42926. };
  42927. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42928. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42929. if (this.attachedElement) {
  42930. return;
  42931. }
  42932. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42933. this.attachedElement = element;
  42934. this.noPreventDefault = noPreventDefault;
  42935. for (var cam in this.attached) {
  42936. this.attached[cam].attachControl(element, noPreventDefault);
  42937. }
  42938. };
  42939. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42940. if (disconnect === void 0) { disconnect = false; }
  42941. if (this.attachedElement !== element) {
  42942. return;
  42943. }
  42944. for (var cam in this.attached) {
  42945. this.attached[cam].detachControl(element);
  42946. if (disconnect) {
  42947. this.attached[cam].camera = null;
  42948. }
  42949. }
  42950. this.attachedElement = null;
  42951. };
  42952. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42953. this.checkInputs = function () { };
  42954. for (var cam in this.attached) {
  42955. var input = this.attached[cam];
  42956. if (input.checkInputs) {
  42957. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42958. }
  42959. }
  42960. };
  42961. /**
  42962. * Remove all attached input methods from a camera
  42963. */
  42964. CameraInputsManager.prototype.clear = function () {
  42965. if (this.attachedElement) {
  42966. this.detachElement(this.attachedElement, true);
  42967. }
  42968. this.attached = {};
  42969. this.attachedElement = null;
  42970. this.checkInputs = function () { };
  42971. };
  42972. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42973. var inputs = {};
  42974. for (var cam in this.attached) {
  42975. var input = this.attached[cam];
  42976. var res = BABYLON.SerializationHelper.Serialize(input);
  42977. inputs[input.getClassName()] = res;
  42978. }
  42979. serializedCamera.inputsmgr = inputs;
  42980. };
  42981. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42982. var parsedInputs = parsedCamera.inputsmgr;
  42983. if (parsedInputs) {
  42984. this.clear();
  42985. for (var n in parsedInputs) {
  42986. var construct = BABYLON.CameraInputTypes[n];
  42987. if (construct) {
  42988. var parsedinput = parsedInputs[n];
  42989. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42990. this.add(input);
  42991. }
  42992. }
  42993. }
  42994. else {
  42995. //2016-03-08 this part is for managing backward compatibility
  42996. for (var n in this.attached) {
  42997. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42998. if (construct) {
  42999. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43000. this.remove(this.attached[n]);
  43001. this.add(input);
  43002. }
  43003. }
  43004. }
  43005. };
  43006. return CameraInputsManager;
  43007. }());
  43008. BABYLON.CameraInputsManager = CameraInputsManager;
  43009. })(BABYLON || (BABYLON = {}));
  43010. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43011. var BABYLON;
  43012. (function (BABYLON) {
  43013. var TargetCamera = /** @class */ (function (_super) {
  43014. __extends(TargetCamera, _super);
  43015. function TargetCamera(name, position, scene) {
  43016. var _this = _super.call(this, name, position, scene) || this;
  43017. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43018. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43019. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43020. _this.speed = 2.0;
  43021. _this.noRotationConstraint = false;
  43022. _this.lockedTarget = null;
  43023. _this._currentTarget = BABYLON.Vector3.Zero();
  43024. _this._viewMatrix = BABYLON.Matrix.Zero();
  43025. _this._camMatrix = BABYLON.Matrix.Zero();
  43026. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43027. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43028. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43029. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43030. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43031. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43032. _this._tempMatrix = BABYLON.Matrix.Zero();
  43033. return _this;
  43034. }
  43035. TargetCamera.prototype.getFrontPosition = function (distance) {
  43036. this.getWorldMatrix();
  43037. var direction = this.getTarget().subtract(this.position);
  43038. direction.normalize();
  43039. direction.scaleInPlace(distance);
  43040. return this.globalPosition.add(direction);
  43041. };
  43042. TargetCamera.prototype._getLockedTargetPosition = function () {
  43043. if (!this.lockedTarget) {
  43044. return null;
  43045. }
  43046. if (this.lockedTarget.absolutePosition) {
  43047. this.lockedTarget.computeWorldMatrix();
  43048. }
  43049. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43050. };
  43051. TargetCamera.prototype.storeState = function () {
  43052. this._storedPosition = this.position.clone();
  43053. this._storedRotation = this.rotation.clone();
  43054. if (this.rotationQuaternion) {
  43055. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43056. }
  43057. return _super.prototype.storeState.call(this);
  43058. };
  43059. /**
  43060. * Restored camera state. You must call storeState() first
  43061. */
  43062. TargetCamera.prototype._restoreStateValues = function () {
  43063. if (!_super.prototype._restoreStateValues.call(this)) {
  43064. return false;
  43065. }
  43066. this.position = this._storedPosition.clone();
  43067. this.rotation = this._storedRotation.clone();
  43068. if (this.rotationQuaternion) {
  43069. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43070. }
  43071. this.cameraDirection.copyFromFloats(0, 0, 0);
  43072. this.cameraRotation.copyFromFloats(0, 0);
  43073. return true;
  43074. };
  43075. // Cache
  43076. TargetCamera.prototype._initCache = function () {
  43077. _super.prototype._initCache.call(this);
  43078. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43079. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43080. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43081. };
  43082. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43083. if (!ignoreParentClass) {
  43084. _super.prototype._updateCache.call(this);
  43085. }
  43086. var lockedTargetPosition = this._getLockedTargetPosition();
  43087. if (!lockedTargetPosition) {
  43088. this._cache.lockedTarget = null;
  43089. }
  43090. else {
  43091. if (!this._cache.lockedTarget) {
  43092. this._cache.lockedTarget = lockedTargetPosition.clone();
  43093. }
  43094. else {
  43095. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43096. }
  43097. }
  43098. this._cache.rotation.copyFrom(this.rotation);
  43099. if (this.rotationQuaternion)
  43100. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43101. };
  43102. // Synchronized
  43103. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43104. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43105. return false;
  43106. }
  43107. var lockedTargetPosition = this._getLockedTargetPosition();
  43108. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43109. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43110. };
  43111. // Methods
  43112. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43113. var engine = this.getEngine();
  43114. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43115. };
  43116. // Target
  43117. TargetCamera.prototype.setTarget = function (target) {
  43118. this.upVector.normalize();
  43119. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43120. this._camMatrix.invert();
  43121. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43122. var vDir = target.subtract(this.position);
  43123. if (vDir.x >= 0.0) {
  43124. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43125. }
  43126. else {
  43127. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43128. }
  43129. this.rotation.z = 0;
  43130. if (isNaN(this.rotation.x)) {
  43131. this.rotation.x = 0;
  43132. }
  43133. if (isNaN(this.rotation.y)) {
  43134. this.rotation.y = 0;
  43135. }
  43136. if (isNaN(this.rotation.z)) {
  43137. this.rotation.z = 0;
  43138. }
  43139. if (this.rotationQuaternion) {
  43140. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43141. }
  43142. };
  43143. /**
  43144. * Return the current target position of the camera. This value is expressed in local space.
  43145. */
  43146. TargetCamera.prototype.getTarget = function () {
  43147. return this._currentTarget;
  43148. };
  43149. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43150. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43151. };
  43152. TargetCamera.prototype._updatePosition = function () {
  43153. if (this.parent) {
  43154. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43155. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43156. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43157. return;
  43158. }
  43159. this.position.addInPlace(this.cameraDirection);
  43160. };
  43161. TargetCamera.prototype._checkInputs = function () {
  43162. var needToMove = this._decideIfNeedsToMove();
  43163. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43164. // Move
  43165. if (needToMove) {
  43166. this._updatePosition();
  43167. }
  43168. // Rotate
  43169. if (needToRotate) {
  43170. this.rotation.x += this.cameraRotation.x;
  43171. this.rotation.y += this.cameraRotation.y;
  43172. //rotate, if quaternion is set and rotation was used
  43173. if (this.rotationQuaternion) {
  43174. var len = this.rotation.lengthSquared();
  43175. if (len) {
  43176. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43177. }
  43178. }
  43179. if (!this.noRotationConstraint) {
  43180. var limit = (Math.PI / 2) * 0.95;
  43181. if (this.rotation.x > limit)
  43182. this.rotation.x = limit;
  43183. if (this.rotation.x < -limit)
  43184. this.rotation.x = -limit;
  43185. }
  43186. }
  43187. // Inertia
  43188. if (needToMove) {
  43189. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43190. this.cameraDirection.x = 0;
  43191. }
  43192. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43193. this.cameraDirection.y = 0;
  43194. }
  43195. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43196. this.cameraDirection.z = 0;
  43197. }
  43198. this.cameraDirection.scaleInPlace(this.inertia);
  43199. }
  43200. if (needToRotate) {
  43201. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43202. this.cameraRotation.x = 0;
  43203. }
  43204. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43205. this.cameraRotation.y = 0;
  43206. }
  43207. this.cameraRotation.scaleInPlace(this.inertia);
  43208. }
  43209. _super.prototype._checkInputs.call(this);
  43210. };
  43211. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43212. if (this.rotationQuaternion) {
  43213. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43214. }
  43215. else {
  43216. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43217. }
  43218. //update the up vector!
  43219. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43220. };
  43221. TargetCamera.prototype._getViewMatrix = function () {
  43222. if (this.lockedTarget) {
  43223. this.setTarget(this._getLockedTargetPosition());
  43224. }
  43225. // Compute
  43226. this._updateCameraRotationMatrix();
  43227. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43228. // Computing target and final matrix
  43229. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43230. if (this.getScene().useRightHandedSystem) {
  43231. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43232. }
  43233. else {
  43234. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43235. }
  43236. return this._viewMatrix;
  43237. };
  43238. /**
  43239. * @override
  43240. * Override Camera.createRigCamera
  43241. */
  43242. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43243. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43244. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43245. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43246. if (!this.rotationQuaternion) {
  43247. this.rotationQuaternion = new BABYLON.Quaternion();
  43248. }
  43249. rigCamera._cameraRigParams = {};
  43250. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43251. }
  43252. return rigCamera;
  43253. }
  43254. return null;
  43255. };
  43256. /**
  43257. * @override
  43258. * Override Camera._updateRigCameras
  43259. */
  43260. TargetCamera.prototype._updateRigCameras = function () {
  43261. var camLeft = this._rigCameras[0];
  43262. var camRight = this._rigCameras[1];
  43263. switch (this.cameraRigMode) {
  43264. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43265. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43266. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43267. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43268. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43269. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43270. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43271. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43272. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43273. camLeft.setTarget(this.getTarget());
  43274. camRight.setTarget(this.getTarget());
  43275. break;
  43276. case BABYLON.Camera.RIG_MODE_VR:
  43277. if (camLeft.rotationQuaternion) {
  43278. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43279. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43280. }
  43281. else {
  43282. camLeft.rotation.copyFrom(this.rotation);
  43283. camRight.rotation.copyFrom(this.rotation);
  43284. }
  43285. camLeft.position.copyFrom(this.position);
  43286. camRight.position.copyFrom(this.position);
  43287. break;
  43288. }
  43289. _super.prototype._updateRigCameras.call(this);
  43290. };
  43291. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43292. if (!this._rigCamTransformMatrix) {
  43293. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43294. }
  43295. var target = this.getTarget();
  43296. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43297. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43298. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43299. };
  43300. TargetCamera.prototype.getClassName = function () {
  43301. return "TargetCamera";
  43302. };
  43303. __decorate([
  43304. BABYLON.serializeAsVector3()
  43305. ], TargetCamera.prototype, "rotation", void 0);
  43306. __decorate([
  43307. BABYLON.serialize()
  43308. ], TargetCamera.prototype, "speed", void 0);
  43309. __decorate([
  43310. BABYLON.serializeAsMeshReference("lockedTargetId")
  43311. ], TargetCamera.prototype, "lockedTarget", void 0);
  43312. return TargetCamera;
  43313. }(BABYLON.Camera));
  43314. BABYLON.TargetCamera = TargetCamera;
  43315. })(BABYLON || (BABYLON = {}));
  43316. //# sourceMappingURL=babylon.targetCamera.js.map
  43317. var BABYLON;
  43318. (function (BABYLON) {
  43319. var FreeCameraMouseInput = /** @class */ (function () {
  43320. function FreeCameraMouseInput(touchEnabled) {
  43321. if (touchEnabled === void 0) { touchEnabled = true; }
  43322. this.touchEnabled = touchEnabled;
  43323. this.buttons = [0, 1, 2];
  43324. this.angularSensibility = 2000.0;
  43325. this.previousPosition = null;
  43326. }
  43327. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43328. var _this = this;
  43329. var engine = this.camera.getEngine();
  43330. if (!this._pointerInput) {
  43331. this._pointerInput = function (p, s) {
  43332. var evt = p.event;
  43333. if (engine.isInVRExclusivePointerMode) {
  43334. return;
  43335. }
  43336. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43337. return;
  43338. }
  43339. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43340. return;
  43341. }
  43342. var srcElement = (evt.srcElement || evt.target);
  43343. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43344. try {
  43345. srcElement.setPointerCapture(evt.pointerId);
  43346. }
  43347. catch (e) {
  43348. //Nothing to do with the error. Execution will continue.
  43349. }
  43350. _this.previousPosition = {
  43351. x: evt.clientX,
  43352. y: evt.clientY
  43353. };
  43354. if (!noPreventDefault) {
  43355. evt.preventDefault();
  43356. element.focus();
  43357. }
  43358. }
  43359. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43360. try {
  43361. srcElement.releasePointerCapture(evt.pointerId);
  43362. }
  43363. catch (e) {
  43364. //Nothing to do with the error.
  43365. }
  43366. _this.previousPosition = null;
  43367. if (!noPreventDefault) {
  43368. evt.preventDefault();
  43369. }
  43370. }
  43371. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43372. if (!_this.previousPosition || engine.isPointerLock) {
  43373. return;
  43374. }
  43375. var offsetX = evt.clientX - _this.previousPosition.x;
  43376. var offsetY = evt.clientY - _this.previousPosition.y;
  43377. if (_this.camera.getScene().useRightHandedSystem) {
  43378. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43379. }
  43380. else {
  43381. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43382. }
  43383. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43384. _this.previousPosition = {
  43385. x: evt.clientX,
  43386. y: evt.clientY
  43387. };
  43388. if (!noPreventDefault) {
  43389. evt.preventDefault();
  43390. }
  43391. }
  43392. };
  43393. }
  43394. this._onMouseMove = function (evt) {
  43395. if (!engine.isPointerLock) {
  43396. return;
  43397. }
  43398. if (engine.isInVRExclusivePointerMode) {
  43399. return;
  43400. }
  43401. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43402. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43403. if (_this.camera.getScene().useRightHandedSystem) {
  43404. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43405. }
  43406. else {
  43407. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43408. }
  43409. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43410. _this.previousPosition = null;
  43411. if (!noPreventDefault) {
  43412. evt.preventDefault();
  43413. }
  43414. };
  43415. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43416. element.addEventListener("mousemove", this._onMouseMove, false);
  43417. };
  43418. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43419. if (this._observer && element) {
  43420. this.camera.getScene().onPointerObservable.remove(this._observer);
  43421. if (this._onMouseMove) {
  43422. element.removeEventListener("mousemove", this._onMouseMove);
  43423. }
  43424. this._observer = null;
  43425. this._onMouseMove = null;
  43426. this.previousPosition = null;
  43427. }
  43428. };
  43429. FreeCameraMouseInput.prototype.getClassName = function () {
  43430. return "FreeCameraMouseInput";
  43431. };
  43432. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43433. return "mouse";
  43434. };
  43435. __decorate([
  43436. BABYLON.serialize()
  43437. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43438. __decorate([
  43439. BABYLON.serialize()
  43440. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43441. return FreeCameraMouseInput;
  43442. }());
  43443. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43444. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43445. })(BABYLON || (BABYLON = {}));
  43446. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43447. var BABYLON;
  43448. (function (BABYLON) {
  43449. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43450. function FreeCameraKeyboardMoveInput() {
  43451. this._keys = new Array();
  43452. this.keysUp = [38];
  43453. this.keysDown = [40];
  43454. this.keysLeft = [37];
  43455. this.keysRight = [39];
  43456. }
  43457. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43458. var _this = this;
  43459. if (this._onCanvasBlurObserver) {
  43460. return;
  43461. }
  43462. this._scene = this.camera.getScene();
  43463. this._engine = this._scene.getEngine();
  43464. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43465. _this._keys = [];
  43466. });
  43467. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43468. var evt = info.event;
  43469. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43470. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43471. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43472. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43473. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43474. var index = _this._keys.indexOf(evt.keyCode);
  43475. if (index === -1) {
  43476. _this._keys.push(evt.keyCode);
  43477. }
  43478. if (!noPreventDefault) {
  43479. evt.preventDefault();
  43480. }
  43481. }
  43482. }
  43483. else {
  43484. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43485. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43486. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43487. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43488. var index = _this._keys.indexOf(evt.keyCode);
  43489. if (index >= 0) {
  43490. _this._keys.splice(index, 1);
  43491. }
  43492. if (!noPreventDefault) {
  43493. evt.preventDefault();
  43494. }
  43495. }
  43496. }
  43497. });
  43498. };
  43499. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43500. if (this._scene) {
  43501. if (this._onKeyboardObserver) {
  43502. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43503. }
  43504. if (this._onCanvasBlurObserver) {
  43505. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43506. }
  43507. this._onKeyboardObserver = null;
  43508. this._onCanvasBlurObserver = null;
  43509. }
  43510. this._keys = [];
  43511. };
  43512. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43513. if (this._onKeyboardObserver) {
  43514. var camera = this.camera;
  43515. // Keyboard
  43516. for (var index = 0; index < this._keys.length; index++) {
  43517. var keyCode = this._keys[index];
  43518. var speed = camera._computeLocalCameraSpeed();
  43519. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43520. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43521. }
  43522. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43523. camera._localDirection.copyFromFloats(0, 0, speed);
  43524. }
  43525. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43526. camera._localDirection.copyFromFloats(speed, 0, 0);
  43527. }
  43528. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43529. camera._localDirection.copyFromFloats(0, 0, -speed);
  43530. }
  43531. if (camera.getScene().useRightHandedSystem) {
  43532. camera._localDirection.z *= -1;
  43533. }
  43534. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43535. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43536. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43537. }
  43538. }
  43539. };
  43540. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43541. return "FreeCameraKeyboardMoveInput";
  43542. };
  43543. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43544. this._keys = [];
  43545. };
  43546. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43547. return "keyboard";
  43548. };
  43549. __decorate([
  43550. BABYLON.serialize()
  43551. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43552. __decorate([
  43553. BABYLON.serialize()
  43554. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43555. __decorate([
  43556. BABYLON.serialize()
  43557. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43558. __decorate([
  43559. BABYLON.serialize()
  43560. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43561. return FreeCameraKeyboardMoveInput;
  43562. }());
  43563. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43564. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43565. })(BABYLON || (BABYLON = {}));
  43566. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43567. var BABYLON;
  43568. (function (BABYLON) {
  43569. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43570. __extends(FreeCameraInputsManager, _super);
  43571. function FreeCameraInputsManager(camera) {
  43572. return _super.call(this, camera) || this;
  43573. }
  43574. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43575. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43576. return this;
  43577. };
  43578. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43579. if (touchEnabled === void 0) { touchEnabled = true; }
  43580. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43581. return this;
  43582. };
  43583. FreeCameraInputsManager.prototype.addGamepad = function () {
  43584. this.add(new BABYLON.FreeCameraGamepadInput());
  43585. return this;
  43586. };
  43587. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43588. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43589. return this;
  43590. };
  43591. FreeCameraInputsManager.prototype.addTouch = function () {
  43592. this.add(new BABYLON.FreeCameraTouchInput());
  43593. return this;
  43594. };
  43595. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43596. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43597. return this;
  43598. };
  43599. return FreeCameraInputsManager;
  43600. }(BABYLON.CameraInputsManager));
  43601. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43602. })(BABYLON || (BABYLON = {}));
  43603. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43604. var BABYLON;
  43605. (function (BABYLON) {
  43606. var FreeCamera = /** @class */ (function (_super) {
  43607. __extends(FreeCamera, _super);
  43608. function FreeCamera(name, position, scene) {
  43609. var _this = _super.call(this, name, position, scene) || this;
  43610. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43611. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43612. _this.checkCollisions = false;
  43613. _this.applyGravity = false;
  43614. _this._needMoveForGravity = false;
  43615. _this._oldPosition = BABYLON.Vector3.Zero();
  43616. _this._diffPosition = BABYLON.Vector3.Zero();
  43617. _this._newPosition = BABYLON.Vector3.Zero();
  43618. // Collisions
  43619. _this._collisionMask = -1;
  43620. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43621. if (collidedMesh === void 0) { collidedMesh = null; }
  43622. //TODO move this to the collision coordinator!
  43623. if (_this.getScene().workerCollisions)
  43624. newPosition.multiplyInPlace(_this._collider._radius);
  43625. var updatePosition = function (newPos) {
  43626. _this._newPosition.copyFrom(newPos);
  43627. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43628. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43629. _this.position.addInPlace(_this._diffPosition);
  43630. if (_this.onCollide && collidedMesh) {
  43631. _this.onCollide(collidedMesh);
  43632. }
  43633. }
  43634. };
  43635. updatePosition(newPosition);
  43636. };
  43637. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43638. _this.inputs.addKeyboard().addMouse();
  43639. return _this;
  43640. }
  43641. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43642. //-- begin properties for backward compatibility for inputs
  43643. /**
  43644. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43645. * Higher values reduce sensitivity.
  43646. */
  43647. get: function () {
  43648. var mouse = this.inputs.attached["mouse"];
  43649. if (mouse)
  43650. return mouse.angularSensibility;
  43651. return 0;
  43652. },
  43653. /**
  43654. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43655. * Higher values reduce sensitivity.
  43656. */
  43657. set: function (value) {
  43658. var mouse = this.inputs.attached["mouse"];
  43659. if (mouse)
  43660. mouse.angularSensibility = value;
  43661. },
  43662. enumerable: true,
  43663. configurable: true
  43664. });
  43665. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43666. get: function () {
  43667. var keyboard = this.inputs.attached["keyboard"];
  43668. if (keyboard)
  43669. return keyboard.keysUp;
  43670. return [];
  43671. },
  43672. set: function (value) {
  43673. var keyboard = this.inputs.attached["keyboard"];
  43674. if (keyboard)
  43675. keyboard.keysUp = value;
  43676. },
  43677. enumerable: true,
  43678. configurable: true
  43679. });
  43680. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43681. get: function () {
  43682. var keyboard = this.inputs.attached["keyboard"];
  43683. if (keyboard)
  43684. return keyboard.keysDown;
  43685. return [];
  43686. },
  43687. set: function (value) {
  43688. var keyboard = this.inputs.attached["keyboard"];
  43689. if (keyboard)
  43690. keyboard.keysDown = value;
  43691. },
  43692. enumerable: true,
  43693. configurable: true
  43694. });
  43695. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43696. get: function () {
  43697. var keyboard = this.inputs.attached["keyboard"];
  43698. if (keyboard)
  43699. return keyboard.keysLeft;
  43700. return [];
  43701. },
  43702. set: function (value) {
  43703. var keyboard = this.inputs.attached["keyboard"];
  43704. if (keyboard)
  43705. keyboard.keysLeft = value;
  43706. },
  43707. enumerable: true,
  43708. configurable: true
  43709. });
  43710. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43711. get: function () {
  43712. var keyboard = this.inputs.attached["keyboard"];
  43713. if (keyboard)
  43714. return keyboard.keysRight;
  43715. return [];
  43716. },
  43717. set: function (value) {
  43718. var keyboard = this.inputs.attached["keyboard"];
  43719. if (keyboard)
  43720. keyboard.keysRight = value;
  43721. },
  43722. enumerable: true,
  43723. configurable: true
  43724. });
  43725. // Controls
  43726. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43727. this.inputs.attachElement(element, noPreventDefault);
  43728. };
  43729. FreeCamera.prototype.detachControl = function (element) {
  43730. this.inputs.detachElement(element);
  43731. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43732. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43733. };
  43734. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43735. get: function () {
  43736. return this._collisionMask;
  43737. },
  43738. set: function (mask) {
  43739. this._collisionMask = !isNaN(mask) ? mask : -1;
  43740. },
  43741. enumerable: true,
  43742. configurable: true
  43743. });
  43744. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43745. var globalPosition;
  43746. if (this.parent) {
  43747. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43748. }
  43749. else {
  43750. globalPosition = this.position;
  43751. }
  43752. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43753. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43754. if (!this._collider) {
  43755. this._collider = new BABYLON.Collider();
  43756. }
  43757. this._collider._radius = this.ellipsoid;
  43758. this._collider.collisionMask = this._collisionMask;
  43759. //no need for clone, as long as gravity is not on.
  43760. var actualDisplacement = displacement;
  43761. //add gravity to the direction to prevent the dual-collision checking
  43762. if (this.applyGravity) {
  43763. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43764. actualDisplacement = displacement.add(this.getScene().gravity);
  43765. }
  43766. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43767. };
  43768. FreeCamera.prototype._checkInputs = function () {
  43769. if (!this._localDirection) {
  43770. this._localDirection = BABYLON.Vector3.Zero();
  43771. this._transformedDirection = BABYLON.Vector3.Zero();
  43772. }
  43773. this.inputs.checkInputs();
  43774. _super.prototype._checkInputs.call(this);
  43775. };
  43776. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43777. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43778. };
  43779. FreeCamera.prototype._updatePosition = function () {
  43780. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43781. this._collideWithWorld(this.cameraDirection);
  43782. }
  43783. else {
  43784. _super.prototype._updatePosition.call(this);
  43785. }
  43786. };
  43787. FreeCamera.prototype.dispose = function () {
  43788. this.inputs.clear();
  43789. _super.prototype.dispose.call(this);
  43790. };
  43791. FreeCamera.prototype.getClassName = function () {
  43792. return "FreeCamera";
  43793. };
  43794. __decorate([
  43795. BABYLON.serializeAsVector3()
  43796. ], FreeCamera.prototype, "ellipsoid", void 0);
  43797. __decorate([
  43798. BABYLON.serializeAsVector3()
  43799. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43800. __decorate([
  43801. BABYLON.serialize()
  43802. ], FreeCamera.prototype, "checkCollisions", void 0);
  43803. __decorate([
  43804. BABYLON.serialize()
  43805. ], FreeCamera.prototype, "applyGravity", void 0);
  43806. return FreeCamera;
  43807. }(BABYLON.TargetCamera));
  43808. BABYLON.FreeCamera = FreeCamera;
  43809. })(BABYLON || (BABYLON = {}));
  43810. //# sourceMappingURL=babylon.freeCamera.js.map
  43811. var BABYLON;
  43812. (function (BABYLON) {
  43813. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43814. function ArcRotateCameraKeyboardMoveInput() {
  43815. this._keys = new Array();
  43816. this.keysUp = [38];
  43817. this.keysDown = [40];
  43818. this.keysLeft = [37];
  43819. this.keysRight = [39];
  43820. this.keysReset = [220];
  43821. this.panningSensibility = 50.0;
  43822. this.zoomingSensibility = 25.0;
  43823. this.useAltToZoom = true;
  43824. }
  43825. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43826. var _this = this;
  43827. if (this._onCanvasBlurObserver) {
  43828. return;
  43829. }
  43830. this._scene = this.camera.getScene();
  43831. this._engine = this._scene.getEngine();
  43832. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43833. _this._keys = [];
  43834. });
  43835. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43836. var evt = info.event;
  43837. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43838. _this._ctrlPressed = evt.ctrlKey;
  43839. _this._altPressed = evt.altKey;
  43840. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43841. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43842. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43843. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43844. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43845. var index = _this._keys.indexOf(evt.keyCode);
  43846. if (index === -1) {
  43847. _this._keys.push(evt.keyCode);
  43848. }
  43849. if (evt.preventDefault) {
  43850. if (!noPreventDefault) {
  43851. evt.preventDefault();
  43852. }
  43853. }
  43854. }
  43855. }
  43856. else {
  43857. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43858. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43859. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43860. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43861. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43862. var index = _this._keys.indexOf(evt.keyCode);
  43863. if (index >= 0) {
  43864. _this._keys.splice(index, 1);
  43865. }
  43866. if (evt.preventDefault) {
  43867. if (!noPreventDefault) {
  43868. evt.preventDefault();
  43869. }
  43870. }
  43871. }
  43872. }
  43873. });
  43874. };
  43875. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43876. if (this._scene) {
  43877. if (this._onKeyboardObserver) {
  43878. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43879. }
  43880. if (this._onCanvasBlurObserver) {
  43881. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43882. }
  43883. this._onKeyboardObserver = null;
  43884. this._onCanvasBlurObserver = null;
  43885. }
  43886. this._keys = [];
  43887. };
  43888. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43889. if (this._onKeyboardObserver) {
  43890. var camera = this.camera;
  43891. for (var index = 0; index < this._keys.length; index++) {
  43892. var keyCode = this._keys[index];
  43893. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43894. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43895. camera.inertialPanningX -= 1 / this.panningSensibility;
  43896. }
  43897. else {
  43898. camera.inertialAlphaOffset -= 0.01;
  43899. }
  43900. }
  43901. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43902. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43903. camera.inertialPanningY += 1 / this.panningSensibility;
  43904. }
  43905. else if (this._altPressed && this.useAltToZoom) {
  43906. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43907. }
  43908. else {
  43909. camera.inertialBetaOffset -= 0.01;
  43910. }
  43911. }
  43912. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43913. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43914. camera.inertialPanningX += 1 / this.panningSensibility;
  43915. }
  43916. else {
  43917. camera.inertialAlphaOffset += 0.01;
  43918. }
  43919. }
  43920. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43921. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43922. camera.inertialPanningY -= 1 / this.panningSensibility;
  43923. }
  43924. else if (this._altPressed && this.useAltToZoom) {
  43925. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43926. }
  43927. else {
  43928. camera.inertialBetaOffset += 0.01;
  43929. }
  43930. }
  43931. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43932. camera.restoreState();
  43933. }
  43934. }
  43935. }
  43936. };
  43937. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43938. return "ArcRotateCameraKeyboardMoveInput";
  43939. };
  43940. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43941. return "keyboard";
  43942. };
  43943. __decorate([
  43944. BABYLON.serialize()
  43945. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43946. __decorate([
  43947. BABYLON.serialize()
  43948. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43949. __decorate([
  43950. BABYLON.serialize()
  43951. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43952. __decorate([
  43953. BABYLON.serialize()
  43954. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43955. __decorate([
  43956. BABYLON.serialize()
  43957. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43958. __decorate([
  43959. BABYLON.serialize()
  43960. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43961. __decorate([
  43962. BABYLON.serialize()
  43963. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43964. __decorate([
  43965. BABYLON.serialize()
  43966. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43967. return ArcRotateCameraKeyboardMoveInput;
  43968. }());
  43969. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43970. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43971. })(BABYLON || (BABYLON = {}));
  43972. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43973. var BABYLON;
  43974. (function (BABYLON) {
  43975. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43976. function ArcRotateCameraMouseWheelInput() {
  43977. this.wheelPrecision = 3.0;
  43978. /**
  43979. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43980. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43981. */
  43982. this.wheelDeltaPercentage = 0;
  43983. }
  43984. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43985. var _this = this;
  43986. this._wheel = function (p, s) {
  43987. //sanity check - this should be a PointerWheel event.
  43988. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43989. return;
  43990. var event = p.event;
  43991. var delta = 0;
  43992. if (event.wheelDelta) {
  43993. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43994. }
  43995. else if (event.detail) {
  43996. delta = -event.detail / _this.wheelPrecision;
  43997. }
  43998. if (delta)
  43999. _this.camera.inertialRadiusOffset += delta;
  44000. if (event.preventDefault) {
  44001. if (!noPreventDefault) {
  44002. event.preventDefault();
  44003. }
  44004. }
  44005. };
  44006. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44007. };
  44008. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44009. if (this._observer && element) {
  44010. this.camera.getScene().onPointerObservable.remove(this._observer);
  44011. this._observer = null;
  44012. this._wheel = null;
  44013. }
  44014. };
  44015. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44016. return "ArcRotateCameraMouseWheelInput";
  44017. };
  44018. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44019. return "mousewheel";
  44020. };
  44021. __decorate([
  44022. BABYLON.serialize()
  44023. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44024. __decorate([
  44025. BABYLON.serialize()
  44026. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44027. return ArcRotateCameraMouseWheelInput;
  44028. }());
  44029. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44030. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44031. })(BABYLON || (BABYLON = {}));
  44032. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44033. var BABYLON;
  44034. (function (BABYLON) {
  44035. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44036. function ArcRotateCameraPointersInput() {
  44037. this.buttons = [0, 1, 2];
  44038. this.angularSensibilityX = 1000.0;
  44039. this.angularSensibilityY = 1000.0;
  44040. this.pinchPrecision = 12.0;
  44041. /**
  44042. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44043. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44044. */
  44045. this.pinchDeltaPercentage = 0;
  44046. this.panningSensibility = 1000.0;
  44047. this.multiTouchPanning = true;
  44048. this.multiTouchPanAndZoom = true;
  44049. this._isPanClick = false;
  44050. this.pinchInwards = true;
  44051. }
  44052. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44053. var _this = this;
  44054. var engine = this.camera.getEngine();
  44055. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44056. var pointA = null;
  44057. var pointB = null;
  44058. var previousPinchSquaredDistance = 0;
  44059. var initialDistance = 0;
  44060. var twoFingerActivityCount = 0;
  44061. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44062. this._pointerInput = function (p, s) {
  44063. var evt = p.event;
  44064. var isTouch = p.event.pointerType === "touch";
  44065. if (engine.isInVRExclusivePointerMode) {
  44066. return;
  44067. }
  44068. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44069. return;
  44070. }
  44071. var srcElement = (evt.srcElement || evt.target);
  44072. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44073. try {
  44074. srcElement.setPointerCapture(evt.pointerId);
  44075. }
  44076. catch (e) {
  44077. //Nothing to do with the error. Execution will continue.
  44078. }
  44079. // Manage panning with pan button click
  44080. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44081. // manage pointers
  44082. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44083. if (pointA === null) {
  44084. pointA = cacheSoloPointer;
  44085. }
  44086. else if (pointB === null) {
  44087. pointB = cacheSoloPointer;
  44088. }
  44089. if (!noPreventDefault) {
  44090. evt.preventDefault();
  44091. element.focus();
  44092. }
  44093. }
  44094. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44095. _this.camera.restoreState();
  44096. }
  44097. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44098. try {
  44099. srcElement.releasePointerCapture(evt.pointerId);
  44100. }
  44101. catch (e) {
  44102. //Nothing to do with the error.
  44103. }
  44104. cacheSoloPointer = null;
  44105. previousPinchSquaredDistance = 0;
  44106. previousMultiTouchPanPosition.isPaning = false;
  44107. previousMultiTouchPanPosition.isPinching = false;
  44108. twoFingerActivityCount = 0;
  44109. initialDistance = 0;
  44110. if (!isTouch) {
  44111. pointB = null; // Mouse and pen are mono pointer
  44112. }
  44113. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44114. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44115. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44116. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44117. if (engine.badOS) {
  44118. pointA = pointB = null;
  44119. }
  44120. else {
  44121. //only remove the impacted pointer in case of multitouch allowing on most
  44122. //platforms switching from rotate to zoom and pan seamlessly.
  44123. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44124. pointA = pointB;
  44125. pointB = null;
  44126. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44127. }
  44128. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44129. pointB = null;
  44130. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44131. }
  44132. else {
  44133. pointA = pointB = null;
  44134. }
  44135. }
  44136. if (!noPreventDefault) {
  44137. evt.preventDefault();
  44138. }
  44139. }
  44140. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44141. if (!noPreventDefault) {
  44142. evt.preventDefault();
  44143. }
  44144. // One button down
  44145. if (pointA && pointB === null && cacheSoloPointer) {
  44146. if (_this.panningSensibility !== 0 &&
  44147. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44148. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44149. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44150. }
  44151. else {
  44152. var offsetX = evt.clientX - cacheSoloPointer.x;
  44153. var offsetY = evt.clientY - cacheSoloPointer.y;
  44154. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44155. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44156. }
  44157. cacheSoloPointer.x = evt.clientX;
  44158. cacheSoloPointer.y = evt.clientY;
  44159. }
  44160. else if (pointA && pointB) {
  44161. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44162. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44163. ed.x = evt.clientX;
  44164. ed.y = evt.clientY;
  44165. var direction = _this.pinchInwards ? 1 : -1;
  44166. var distX = pointA.x - pointB.x;
  44167. var distY = pointA.y - pointB.y;
  44168. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44169. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44170. if (previousPinchSquaredDistance === 0) {
  44171. initialDistance = pinchDistance;
  44172. previousPinchSquaredDistance = pinchSquaredDistance;
  44173. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44174. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44175. return;
  44176. }
  44177. if (_this.multiTouchPanAndZoom) {
  44178. if (_this.pinchDeltaPercentage) {
  44179. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44180. }
  44181. else {
  44182. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44183. (_this.pinchPrecision *
  44184. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44185. direction);
  44186. }
  44187. if (_this.panningSensibility !== 0) {
  44188. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44189. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44190. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44191. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44192. previousMultiTouchPanPosition.x = pointersCenterX;
  44193. previousMultiTouchPanPosition.y = pointersCenterY;
  44194. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44195. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44196. }
  44197. }
  44198. else {
  44199. twoFingerActivityCount++;
  44200. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44201. if (_this.pinchDeltaPercentage) {
  44202. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44203. }
  44204. else {
  44205. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44206. (_this.pinchPrecision *
  44207. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44208. direction);
  44209. }
  44210. previousMultiTouchPanPosition.isPaning = false;
  44211. previousMultiTouchPanPosition.isPinching = true;
  44212. }
  44213. else {
  44214. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44215. if (!previousMultiTouchPanPosition.isPaning) {
  44216. previousMultiTouchPanPosition.isPaning = true;
  44217. previousMultiTouchPanPosition.isPinching = false;
  44218. previousMultiTouchPanPosition.x = ed.x;
  44219. previousMultiTouchPanPosition.y = ed.y;
  44220. return;
  44221. }
  44222. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44223. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44224. }
  44225. }
  44226. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44227. previousMultiTouchPanPosition.x = ed.x;
  44228. previousMultiTouchPanPosition.y = ed.y;
  44229. }
  44230. }
  44231. previousPinchSquaredDistance = pinchSquaredDistance;
  44232. }
  44233. }
  44234. };
  44235. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44236. this._onContextMenu = function (evt) {
  44237. evt.preventDefault();
  44238. };
  44239. if (!this.camera._useCtrlForPanning) {
  44240. element.addEventListener("contextmenu", this._onContextMenu, false);
  44241. }
  44242. this._onLostFocus = function () {
  44243. //this._keys = [];
  44244. pointA = pointB = null;
  44245. previousPinchSquaredDistance = 0;
  44246. previousMultiTouchPanPosition.isPaning = false;
  44247. previousMultiTouchPanPosition.isPinching = false;
  44248. twoFingerActivityCount = 0;
  44249. cacheSoloPointer = null;
  44250. initialDistance = 0;
  44251. };
  44252. this._onMouseMove = function (evt) {
  44253. if (!engine.isPointerLock) {
  44254. return;
  44255. }
  44256. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44257. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44258. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44259. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44260. if (!noPreventDefault) {
  44261. evt.preventDefault();
  44262. }
  44263. };
  44264. this._onGestureStart = function (e) {
  44265. if (window.MSGesture === undefined) {
  44266. return;
  44267. }
  44268. if (!_this._MSGestureHandler) {
  44269. _this._MSGestureHandler = new MSGesture();
  44270. _this._MSGestureHandler.target = element;
  44271. }
  44272. _this._MSGestureHandler.addPointer(e.pointerId);
  44273. };
  44274. this._onGesture = function (e) {
  44275. _this.camera.radius *= e.scale;
  44276. if (e.preventDefault) {
  44277. if (!noPreventDefault) {
  44278. e.stopPropagation();
  44279. e.preventDefault();
  44280. }
  44281. }
  44282. };
  44283. element.addEventListener("mousemove", this._onMouseMove, false);
  44284. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44285. element.addEventListener("MSGestureChange", this._onGesture, false);
  44286. BABYLON.Tools.RegisterTopRootEvents([
  44287. { name: "blur", handler: this._onLostFocus }
  44288. ]);
  44289. };
  44290. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44291. if (this._onLostFocus) {
  44292. BABYLON.Tools.UnregisterTopRootEvents([
  44293. { name: "blur", handler: this._onLostFocus }
  44294. ]);
  44295. }
  44296. if (element && this._observer) {
  44297. this.camera.getScene().onPointerObservable.remove(this._observer);
  44298. this._observer = null;
  44299. if (this._onContextMenu) {
  44300. element.removeEventListener("contextmenu", this._onContextMenu);
  44301. }
  44302. if (this._onMouseMove) {
  44303. element.removeEventListener("mousemove", this._onMouseMove);
  44304. }
  44305. if (this._onGestureStart) {
  44306. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44307. }
  44308. if (this._onGesture) {
  44309. element.removeEventListener("MSGestureChange", this._onGesture);
  44310. }
  44311. this._isPanClick = false;
  44312. this.pinchInwards = true;
  44313. this._onMouseMove = null;
  44314. this._onGestureStart = null;
  44315. this._onGesture = null;
  44316. this._MSGestureHandler = null;
  44317. this._onLostFocus = null;
  44318. this._onContextMenu = null;
  44319. }
  44320. };
  44321. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44322. return "ArcRotateCameraPointersInput";
  44323. };
  44324. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44325. return "pointers";
  44326. };
  44327. __decorate([
  44328. BABYLON.serialize()
  44329. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44330. __decorate([
  44331. BABYLON.serialize()
  44332. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44333. __decorate([
  44334. BABYLON.serialize()
  44335. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44336. __decorate([
  44337. BABYLON.serialize()
  44338. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44339. __decorate([
  44340. BABYLON.serialize()
  44341. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44342. __decorate([
  44343. BABYLON.serialize()
  44344. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44345. __decorate([
  44346. BABYLON.serialize()
  44347. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44348. __decorate([
  44349. BABYLON.serialize()
  44350. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44351. return ArcRotateCameraPointersInput;
  44352. }());
  44353. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44354. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44355. })(BABYLON || (BABYLON = {}));
  44356. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44357. var BABYLON;
  44358. (function (BABYLON) {
  44359. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44360. __extends(ArcRotateCameraInputsManager, _super);
  44361. function ArcRotateCameraInputsManager(camera) {
  44362. return _super.call(this, camera) || this;
  44363. }
  44364. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44365. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44366. return this;
  44367. };
  44368. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44369. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44370. return this;
  44371. };
  44372. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44373. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44374. return this;
  44375. };
  44376. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44377. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44378. return this;
  44379. };
  44380. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44381. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44382. return this;
  44383. };
  44384. return ArcRotateCameraInputsManager;
  44385. }(BABYLON.CameraInputsManager));
  44386. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44387. })(BABYLON || (BABYLON = {}));
  44388. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44389. var BABYLON;
  44390. (function (BABYLON) {
  44391. var ArcRotateCamera = /** @class */ (function (_super) {
  44392. __extends(ArcRotateCamera, _super);
  44393. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44394. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44395. _this.inertialAlphaOffset = 0;
  44396. _this.inertialBetaOffset = 0;
  44397. _this.inertialRadiusOffset = 0;
  44398. _this.lowerAlphaLimit = null;
  44399. _this.upperAlphaLimit = null;
  44400. _this.lowerBetaLimit = 0.01;
  44401. _this.upperBetaLimit = Math.PI;
  44402. _this.lowerRadiusLimit = null;
  44403. _this.upperRadiusLimit = null;
  44404. _this.inertialPanningX = 0;
  44405. _this.inertialPanningY = 0;
  44406. _this.pinchToPanMaxDistance = 20;
  44407. _this.panningDistanceLimit = null;
  44408. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44409. _this.panningInertia = 0.9;
  44410. //-- end properties for backward compatibility for inputs
  44411. _this.zoomOnFactor = 1;
  44412. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44413. _this.allowUpsideDown = true;
  44414. _this._viewMatrix = new BABYLON.Matrix();
  44415. // Panning
  44416. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44417. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44418. _this.checkCollisions = false;
  44419. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44420. _this._previousPosition = BABYLON.Vector3.Zero();
  44421. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44422. _this._newPosition = BABYLON.Vector3.Zero();
  44423. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44424. if (collidedMesh === void 0) { collidedMesh = null; }
  44425. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44426. newPosition.multiplyInPlace(_this._collider._radius);
  44427. }
  44428. if (!collidedMesh) {
  44429. _this._previousPosition.copyFrom(_this.position);
  44430. }
  44431. else {
  44432. _this.setPosition(newPosition);
  44433. if (_this.onCollide) {
  44434. _this.onCollide(collidedMesh);
  44435. }
  44436. }
  44437. // Recompute because of constraints
  44438. var cosa = Math.cos(_this.alpha);
  44439. var sina = Math.sin(_this.alpha);
  44440. var cosb = Math.cos(_this.beta);
  44441. var sinb = Math.sin(_this.beta);
  44442. if (sinb === 0) {
  44443. sinb = 0.0001;
  44444. }
  44445. var target = _this._getTargetPosition();
  44446. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44447. _this.position.copyFrom(_this._newPosition);
  44448. var up = _this.upVector;
  44449. if (_this.allowUpsideDown && _this.beta < 0) {
  44450. up = up.clone();
  44451. up = up.negate();
  44452. }
  44453. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44454. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44455. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44456. _this._collisionTriggered = false;
  44457. };
  44458. _this._target = BABYLON.Vector3.Zero();
  44459. if (target) {
  44460. _this.setTarget(target);
  44461. }
  44462. _this.alpha = alpha;
  44463. _this.beta = beta;
  44464. _this.radius = radius;
  44465. _this.getViewMatrix();
  44466. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44467. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44468. return _this;
  44469. }
  44470. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44471. get: function () {
  44472. return this._target;
  44473. },
  44474. set: function (value) {
  44475. this.setTarget(value);
  44476. },
  44477. enumerable: true,
  44478. configurable: true
  44479. });
  44480. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44481. //-- begin properties for backward compatibility for inputs
  44482. get: function () {
  44483. var pointers = this.inputs.attached["pointers"];
  44484. if (pointers)
  44485. return pointers.angularSensibilityX;
  44486. return 0;
  44487. },
  44488. set: function (value) {
  44489. var pointers = this.inputs.attached["pointers"];
  44490. if (pointers) {
  44491. pointers.angularSensibilityX = value;
  44492. }
  44493. },
  44494. enumerable: true,
  44495. configurable: true
  44496. });
  44497. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44498. get: function () {
  44499. var pointers = this.inputs.attached["pointers"];
  44500. if (pointers)
  44501. return pointers.angularSensibilityY;
  44502. return 0;
  44503. },
  44504. set: function (value) {
  44505. var pointers = this.inputs.attached["pointers"];
  44506. if (pointers) {
  44507. pointers.angularSensibilityY = value;
  44508. }
  44509. },
  44510. enumerable: true,
  44511. configurable: true
  44512. });
  44513. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44514. get: function () {
  44515. var pointers = this.inputs.attached["pointers"];
  44516. if (pointers)
  44517. return pointers.pinchPrecision;
  44518. return 0;
  44519. },
  44520. set: function (value) {
  44521. var pointers = this.inputs.attached["pointers"];
  44522. if (pointers) {
  44523. pointers.pinchPrecision = value;
  44524. }
  44525. },
  44526. enumerable: true,
  44527. configurable: true
  44528. });
  44529. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44530. get: function () {
  44531. var pointers = this.inputs.attached["pointers"];
  44532. if (pointers)
  44533. return pointers.pinchDeltaPercentage;
  44534. return 0;
  44535. },
  44536. set: function (value) {
  44537. var pointers = this.inputs.attached["pointers"];
  44538. if (pointers) {
  44539. pointers.pinchDeltaPercentage = value;
  44540. }
  44541. },
  44542. enumerable: true,
  44543. configurable: true
  44544. });
  44545. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44546. get: function () {
  44547. var pointers = this.inputs.attached["pointers"];
  44548. if (pointers)
  44549. return pointers.panningSensibility;
  44550. return 0;
  44551. },
  44552. set: function (value) {
  44553. var pointers = this.inputs.attached["pointers"];
  44554. if (pointers) {
  44555. pointers.panningSensibility = value;
  44556. }
  44557. },
  44558. enumerable: true,
  44559. configurable: true
  44560. });
  44561. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44562. get: function () {
  44563. var keyboard = this.inputs.attached["keyboard"];
  44564. if (keyboard)
  44565. return keyboard.keysUp;
  44566. return [];
  44567. },
  44568. set: function (value) {
  44569. var keyboard = this.inputs.attached["keyboard"];
  44570. if (keyboard)
  44571. keyboard.keysUp = value;
  44572. },
  44573. enumerable: true,
  44574. configurable: true
  44575. });
  44576. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44577. get: function () {
  44578. var keyboard = this.inputs.attached["keyboard"];
  44579. if (keyboard)
  44580. return keyboard.keysDown;
  44581. return [];
  44582. },
  44583. set: function (value) {
  44584. var keyboard = this.inputs.attached["keyboard"];
  44585. if (keyboard)
  44586. keyboard.keysDown = value;
  44587. },
  44588. enumerable: true,
  44589. configurable: true
  44590. });
  44591. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44592. get: function () {
  44593. var keyboard = this.inputs.attached["keyboard"];
  44594. if (keyboard)
  44595. return keyboard.keysLeft;
  44596. return [];
  44597. },
  44598. set: function (value) {
  44599. var keyboard = this.inputs.attached["keyboard"];
  44600. if (keyboard)
  44601. keyboard.keysLeft = value;
  44602. },
  44603. enumerable: true,
  44604. configurable: true
  44605. });
  44606. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44607. get: function () {
  44608. var keyboard = this.inputs.attached["keyboard"];
  44609. if (keyboard)
  44610. return keyboard.keysRight;
  44611. return [];
  44612. },
  44613. set: function (value) {
  44614. var keyboard = this.inputs.attached["keyboard"];
  44615. if (keyboard)
  44616. keyboard.keysRight = value;
  44617. },
  44618. enumerable: true,
  44619. configurable: true
  44620. });
  44621. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44622. get: function () {
  44623. var mousewheel = this.inputs.attached["mousewheel"];
  44624. if (mousewheel)
  44625. return mousewheel.wheelPrecision;
  44626. return 0;
  44627. },
  44628. set: function (value) {
  44629. var mousewheel = this.inputs.attached["mousewheel"];
  44630. if (mousewheel)
  44631. mousewheel.wheelPrecision = value;
  44632. },
  44633. enumerable: true,
  44634. configurable: true
  44635. });
  44636. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44637. get: function () {
  44638. var mousewheel = this.inputs.attached["mousewheel"];
  44639. if (mousewheel)
  44640. return mousewheel.wheelDeltaPercentage;
  44641. return 0;
  44642. },
  44643. set: function (value) {
  44644. var mousewheel = this.inputs.attached["mousewheel"];
  44645. if (mousewheel)
  44646. mousewheel.wheelDeltaPercentage = value;
  44647. },
  44648. enumerable: true,
  44649. configurable: true
  44650. });
  44651. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44652. get: function () {
  44653. return this._bouncingBehavior;
  44654. },
  44655. enumerable: true,
  44656. configurable: true
  44657. });
  44658. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44659. get: function () {
  44660. return this._bouncingBehavior != null;
  44661. },
  44662. set: function (value) {
  44663. if (value === this.useBouncingBehavior) {
  44664. return;
  44665. }
  44666. if (value) {
  44667. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44668. this.addBehavior(this._bouncingBehavior);
  44669. }
  44670. else if (this._bouncingBehavior) {
  44671. this.removeBehavior(this._bouncingBehavior);
  44672. this._bouncingBehavior = null;
  44673. }
  44674. },
  44675. enumerable: true,
  44676. configurable: true
  44677. });
  44678. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44679. get: function () {
  44680. return this._framingBehavior;
  44681. },
  44682. enumerable: true,
  44683. configurable: true
  44684. });
  44685. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44686. get: function () {
  44687. return this._framingBehavior != null;
  44688. },
  44689. set: function (value) {
  44690. if (value === this.useFramingBehavior) {
  44691. return;
  44692. }
  44693. if (value) {
  44694. this._framingBehavior = new BABYLON.FramingBehavior();
  44695. this.addBehavior(this._framingBehavior);
  44696. }
  44697. else if (this._framingBehavior) {
  44698. this.removeBehavior(this._framingBehavior);
  44699. this._framingBehavior = null;
  44700. }
  44701. },
  44702. enumerable: true,
  44703. configurable: true
  44704. });
  44705. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44706. get: function () {
  44707. return this._autoRotationBehavior;
  44708. },
  44709. enumerable: true,
  44710. configurable: true
  44711. });
  44712. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44713. get: function () {
  44714. return this._autoRotationBehavior != null;
  44715. },
  44716. set: function (value) {
  44717. if (value === this.useAutoRotationBehavior) {
  44718. return;
  44719. }
  44720. if (value) {
  44721. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44722. this.addBehavior(this._autoRotationBehavior);
  44723. }
  44724. else if (this._autoRotationBehavior) {
  44725. this.removeBehavior(this._autoRotationBehavior);
  44726. this._autoRotationBehavior = null;
  44727. }
  44728. },
  44729. enumerable: true,
  44730. configurable: true
  44731. });
  44732. // Cache
  44733. ArcRotateCamera.prototype._initCache = function () {
  44734. _super.prototype._initCache.call(this);
  44735. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44736. this._cache.alpha = undefined;
  44737. this._cache.beta = undefined;
  44738. this._cache.radius = undefined;
  44739. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44740. };
  44741. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44742. if (!ignoreParentClass) {
  44743. _super.prototype._updateCache.call(this);
  44744. }
  44745. this._cache._target.copyFrom(this._getTargetPosition());
  44746. this._cache.alpha = this.alpha;
  44747. this._cache.beta = this.beta;
  44748. this._cache.radius = this.radius;
  44749. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44750. };
  44751. ArcRotateCamera.prototype._getTargetPosition = function () {
  44752. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44753. var pos = this._targetHost.getAbsolutePosition();
  44754. if (this._targetBoundingCenter) {
  44755. pos.addToRef(this._targetBoundingCenter, this._target);
  44756. }
  44757. else {
  44758. this._target.copyFrom(pos);
  44759. }
  44760. }
  44761. var lockedTargetPosition = this._getLockedTargetPosition();
  44762. if (lockedTargetPosition) {
  44763. return lockedTargetPosition;
  44764. }
  44765. return this._target;
  44766. };
  44767. ArcRotateCamera.prototype.storeState = function () {
  44768. this._storedAlpha = this.alpha;
  44769. this._storedBeta = this.beta;
  44770. this._storedRadius = this.radius;
  44771. this._storedTarget = this._getTargetPosition().clone();
  44772. return _super.prototype.storeState.call(this);
  44773. };
  44774. /**
  44775. * Restored camera state. You must call storeState() first
  44776. */
  44777. ArcRotateCamera.prototype._restoreStateValues = function () {
  44778. if (!_super.prototype._restoreStateValues.call(this)) {
  44779. return false;
  44780. }
  44781. this.alpha = this._storedAlpha;
  44782. this.beta = this._storedBeta;
  44783. this.radius = this._storedRadius;
  44784. this.setTarget(this._storedTarget.clone());
  44785. this.inertialAlphaOffset = 0;
  44786. this.inertialBetaOffset = 0;
  44787. this.inertialRadiusOffset = 0;
  44788. this.inertialPanningX = 0;
  44789. this.inertialPanningY = 0;
  44790. return true;
  44791. };
  44792. // Synchronized
  44793. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44794. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44795. return false;
  44796. return this._cache._target.equals(this._getTargetPosition())
  44797. && this._cache.alpha === this.alpha
  44798. && this._cache.beta === this.beta
  44799. && this._cache.radius === this.radius
  44800. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44801. };
  44802. // Methods
  44803. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44804. var _this = this;
  44805. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44806. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44807. this._useCtrlForPanning = useCtrlForPanning;
  44808. this._panningMouseButton = panningMouseButton;
  44809. this.inputs.attachElement(element, noPreventDefault);
  44810. this._reset = function () {
  44811. _this.inertialAlphaOffset = 0;
  44812. _this.inertialBetaOffset = 0;
  44813. _this.inertialRadiusOffset = 0;
  44814. _this.inertialPanningX = 0;
  44815. _this.inertialPanningY = 0;
  44816. };
  44817. };
  44818. ArcRotateCamera.prototype.detachControl = function (element) {
  44819. this.inputs.detachElement(element);
  44820. if (this._reset) {
  44821. this._reset();
  44822. }
  44823. };
  44824. ArcRotateCamera.prototype._checkInputs = function () {
  44825. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44826. if (this._collisionTriggered) {
  44827. return;
  44828. }
  44829. this.inputs.checkInputs();
  44830. // Inertia
  44831. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44832. if (this.getScene().useRightHandedSystem) {
  44833. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44834. }
  44835. else {
  44836. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44837. }
  44838. this.beta += this.inertialBetaOffset;
  44839. this.radius -= this.inertialRadiusOffset;
  44840. this.inertialAlphaOffset *= this.inertia;
  44841. this.inertialBetaOffset *= this.inertia;
  44842. this.inertialRadiusOffset *= this.inertia;
  44843. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44844. this.inertialAlphaOffset = 0;
  44845. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44846. this.inertialBetaOffset = 0;
  44847. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44848. this.inertialRadiusOffset = 0;
  44849. }
  44850. // Panning inertia
  44851. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44852. if (!this._localDirection) {
  44853. this._localDirection = BABYLON.Vector3.Zero();
  44854. this._transformedDirection = BABYLON.Vector3.Zero();
  44855. }
  44856. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44857. this._localDirection.multiplyInPlace(this.panningAxis);
  44858. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44859. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44860. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44861. if (!this.panningAxis.y) {
  44862. this._transformedDirection.y = 0;
  44863. }
  44864. if (!this._targetHost) {
  44865. if (this.panningDistanceLimit) {
  44866. this._transformedDirection.addInPlace(this._target);
  44867. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44868. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44869. this._target.copyFrom(this._transformedDirection);
  44870. }
  44871. }
  44872. else {
  44873. this._target.addInPlace(this._transformedDirection);
  44874. }
  44875. }
  44876. this.inertialPanningX *= this.panningInertia;
  44877. this.inertialPanningY *= this.panningInertia;
  44878. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44879. this.inertialPanningX = 0;
  44880. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44881. this.inertialPanningY = 0;
  44882. }
  44883. // Limits
  44884. this._checkLimits();
  44885. _super.prototype._checkInputs.call(this);
  44886. };
  44887. ArcRotateCamera.prototype._checkLimits = function () {
  44888. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44889. if (this.allowUpsideDown && this.beta > Math.PI) {
  44890. this.beta = this.beta - (2 * Math.PI);
  44891. }
  44892. }
  44893. else {
  44894. if (this.beta < this.lowerBetaLimit) {
  44895. this.beta = this.lowerBetaLimit;
  44896. }
  44897. }
  44898. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44899. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44900. this.beta = this.beta + (2 * Math.PI);
  44901. }
  44902. }
  44903. else {
  44904. if (this.beta > this.upperBetaLimit) {
  44905. this.beta = this.upperBetaLimit;
  44906. }
  44907. }
  44908. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44909. this.alpha = this.lowerAlphaLimit;
  44910. }
  44911. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44912. this.alpha = this.upperAlphaLimit;
  44913. }
  44914. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44915. this.radius = this.lowerRadiusLimit;
  44916. }
  44917. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44918. this.radius = this.upperRadiusLimit;
  44919. }
  44920. };
  44921. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44922. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44923. this.radius = radiusv3.length();
  44924. if (this.radius === 0) {
  44925. this.radius = 0.0001; // Just to avoid division by zero
  44926. }
  44927. // Alpha
  44928. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44929. if (radiusv3.z < 0) {
  44930. this.alpha = 2 * Math.PI - this.alpha;
  44931. }
  44932. // Beta
  44933. this.beta = Math.acos(radiusv3.y / this.radius);
  44934. this._checkLimits();
  44935. };
  44936. ArcRotateCamera.prototype.setPosition = function (position) {
  44937. if (this.position.equals(position)) {
  44938. return;
  44939. }
  44940. this.position.copyFrom(position);
  44941. this.rebuildAnglesAndRadius();
  44942. };
  44943. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44944. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44945. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44946. if (target.getBoundingInfo) {
  44947. if (toBoundingCenter) {
  44948. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44949. }
  44950. else {
  44951. this._targetBoundingCenter = null;
  44952. }
  44953. this._targetHost = target;
  44954. this._target = this._getTargetPosition();
  44955. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44956. }
  44957. else {
  44958. var newTarget = target;
  44959. var currentTarget = this._getTargetPosition();
  44960. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44961. return;
  44962. }
  44963. this._targetHost = null;
  44964. this._target = newTarget;
  44965. this._targetBoundingCenter = null;
  44966. this.onMeshTargetChangedObservable.notifyObservers(null);
  44967. }
  44968. this.rebuildAnglesAndRadius();
  44969. };
  44970. ArcRotateCamera.prototype._getViewMatrix = function () {
  44971. // Compute
  44972. var cosa = Math.cos(this.alpha);
  44973. var sina = Math.sin(this.alpha);
  44974. var cosb = Math.cos(this.beta);
  44975. var sinb = Math.sin(this.beta);
  44976. if (sinb === 0) {
  44977. sinb = 0.0001;
  44978. }
  44979. var target = this._getTargetPosition();
  44980. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44981. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44982. if (!this._collider) {
  44983. this._collider = new BABYLON.Collider();
  44984. }
  44985. this._collider._radius = this.collisionRadius;
  44986. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44987. this._collisionTriggered = true;
  44988. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44989. }
  44990. else {
  44991. this.position.copyFrom(this._newPosition);
  44992. var up = this.upVector;
  44993. if (this.allowUpsideDown && sinb < 0) {
  44994. up = up.clone();
  44995. up = up.negate();
  44996. }
  44997. if (this.getScene().useRightHandedSystem) {
  44998. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44999. }
  45000. else {
  45001. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45002. }
  45003. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45004. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45005. }
  45006. this._currentTarget = target;
  45007. return this._viewMatrix;
  45008. };
  45009. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45010. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45011. meshes = meshes || this.getScene().meshes;
  45012. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45013. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45014. this.radius = distance * this.zoomOnFactor;
  45015. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45016. };
  45017. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45018. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45019. var meshesOrMinMaxVector;
  45020. var distance;
  45021. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45022. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45023. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45024. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45025. }
  45026. else {
  45027. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45028. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45029. distance = minMaxVectorAndDistance.distance;
  45030. }
  45031. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45032. if (!doNotUpdateMaxZ) {
  45033. this.maxZ = distance * 2;
  45034. }
  45035. };
  45036. /**
  45037. * @override
  45038. * Override Camera.createRigCamera
  45039. */
  45040. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45041. var alphaShift = 0;
  45042. switch (this.cameraRigMode) {
  45043. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45044. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45045. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45046. case BABYLON.Camera.RIG_MODE_VR:
  45047. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45048. break;
  45049. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45050. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45051. break;
  45052. }
  45053. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45054. rigCam._cameraRigParams = {};
  45055. return rigCam;
  45056. };
  45057. /**
  45058. * @override
  45059. * Override Camera._updateRigCameras
  45060. */
  45061. ArcRotateCamera.prototype._updateRigCameras = function () {
  45062. var camLeft = this._rigCameras[0];
  45063. var camRight = this._rigCameras[1];
  45064. camLeft.beta = camRight.beta = this.beta;
  45065. camLeft.radius = camRight.radius = this.radius;
  45066. switch (this.cameraRigMode) {
  45067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45068. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45069. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45070. case BABYLON.Camera.RIG_MODE_VR:
  45071. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45072. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45073. break;
  45074. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45075. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45076. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45077. break;
  45078. }
  45079. _super.prototype._updateRigCameras.call(this);
  45080. };
  45081. ArcRotateCamera.prototype.dispose = function () {
  45082. this.inputs.clear();
  45083. _super.prototype.dispose.call(this);
  45084. };
  45085. ArcRotateCamera.prototype.getClassName = function () {
  45086. return "ArcRotateCamera";
  45087. };
  45088. __decorate([
  45089. BABYLON.serialize()
  45090. ], ArcRotateCamera.prototype, "alpha", void 0);
  45091. __decorate([
  45092. BABYLON.serialize()
  45093. ], ArcRotateCamera.prototype, "beta", void 0);
  45094. __decorate([
  45095. BABYLON.serialize()
  45096. ], ArcRotateCamera.prototype, "radius", void 0);
  45097. __decorate([
  45098. BABYLON.serializeAsVector3("target")
  45099. ], ArcRotateCamera.prototype, "_target", void 0);
  45100. __decorate([
  45101. BABYLON.serialize()
  45102. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45103. __decorate([
  45104. BABYLON.serialize()
  45105. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45106. __decorate([
  45107. BABYLON.serialize()
  45108. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45109. __decorate([
  45110. BABYLON.serialize()
  45111. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45112. __decorate([
  45113. BABYLON.serialize()
  45114. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45115. __decorate([
  45116. BABYLON.serialize()
  45117. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45118. __decorate([
  45119. BABYLON.serialize()
  45120. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45121. __decorate([
  45122. BABYLON.serialize()
  45123. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45124. __decorate([
  45125. BABYLON.serialize()
  45126. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45127. __decorate([
  45128. BABYLON.serialize()
  45129. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45130. __decorate([
  45131. BABYLON.serialize()
  45132. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45133. __decorate([
  45134. BABYLON.serialize()
  45135. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45136. __decorate([
  45137. BABYLON.serialize()
  45138. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45139. __decorate([
  45140. BABYLON.serializeAsVector3()
  45141. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45142. __decorate([
  45143. BABYLON.serialize()
  45144. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45145. __decorate([
  45146. BABYLON.serialize()
  45147. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45148. __decorate([
  45149. BABYLON.serialize()
  45150. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45151. return ArcRotateCamera;
  45152. }(BABYLON.TargetCamera));
  45153. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45154. })(BABYLON || (BABYLON = {}));
  45155. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45156. var BABYLON;
  45157. (function (BABYLON) {
  45158. /**
  45159. * The HemisphericLight simulates the ambient environment light,
  45160. * so the passed direction is the light reflection direction, not the incoming direction.
  45161. */
  45162. var HemisphericLight = /** @class */ (function (_super) {
  45163. __extends(HemisphericLight, _super);
  45164. /**
  45165. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45166. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45167. * The HemisphericLight can't cast shadows.
  45168. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45169. * @param name The friendly name of the light
  45170. * @param direction The direction of the light reflection
  45171. * @param scene The scene the light belongs to
  45172. */
  45173. function HemisphericLight(name, direction, scene) {
  45174. var _this = _super.call(this, name, scene) || this;
  45175. /**
  45176. * The groundColor is the light in the opposite direction to the one specified during creation.
  45177. * 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.
  45178. */
  45179. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45180. _this.direction = direction || BABYLON.Vector3.Up();
  45181. return _this;
  45182. }
  45183. HemisphericLight.prototype._buildUniformLayout = function () {
  45184. this._uniformBuffer.addUniform("vLightData", 4);
  45185. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45186. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45187. this._uniformBuffer.addUniform("vLightGround", 3);
  45188. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45189. this._uniformBuffer.addUniform("depthValues", 2);
  45190. this._uniformBuffer.create();
  45191. };
  45192. /**
  45193. * Returns the string "HemisphericLight".
  45194. * @return The class name
  45195. */
  45196. HemisphericLight.prototype.getClassName = function () {
  45197. return "HemisphericLight";
  45198. };
  45199. /**
  45200. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45201. * Returns the updated direction.
  45202. * @param target The target the direction should point to
  45203. * @return The computed direction
  45204. */
  45205. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45206. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45207. return this.direction;
  45208. };
  45209. /**
  45210. * Returns the shadow generator associated to the light.
  45211. * @returns Always null for hemispheric lights because it does not support shadows.
  45212. */
  45213. HemisphericLight.prototype.getShadowGenerator = function () {
  45214. return null;
  45215. };
  45216. /**
  45217. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45218. * @param effect The effect to update
  45219. * @param lightIndex The index of the light in the effect to update
  45220. * @returns The hemispheric light
  45221. */
  45222. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45223. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45224. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45225. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45226. return this;
  45227. };
  45228. /**
  45229. * @ignore internal use only.
  45230. */
  45231. HemisphericLight.prototype._getWorldMatrix = function () {
  45232. if (!this._worldMatrix) {
  45233. this._worldMatrix = BABYLON.Matrix.Identity();
  45234. }
  45235. return this._worldMatrix;
  45236. };
  45237. /**
  45238. * Returns the integer 3.
  45239. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45240. */
  45241. HemisphericLight.prototype.getTypeID = function () {
  45242. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45243. };
  45244. __decorate([
  45245. BABYLON.serializeAsColor3()
  45246. ], HemisphericLight.prototype, "groundColor", void 0);
  45247. __decorate([
  45248. BABYLON.serializeAsVector3()
  45249. ], HemisphericLight.prototype, "direction", void 0);
  45250. return HemisphericLight;
  45251. }(BABYLON.Light));
  45252. BABYLON.HemisphericLight = HemisphericLight;
  45253. })(BABYLON || (BABYLON = {}));
  45254. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45255. var BABYLON;
  45256. (function (BABYLON) {
  45257. /**
  45258. * Base implementation of @see IShadowLight
  45259. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45260. */
  45261. var ShadowLight = /** @class */ (function (_super) {
  45262. __extends(ShadowLight, _super);
  45263. function ShadowLight() {
  45264. var _this = _super !== null && _super.apply(this, arguments) || this;
  45265. _this._needProjectionMatrixCompute = true;
  45266. return _this;
  45267. }
  45268. ShadowLight.prototype._setPosition = function (value) {
  45269. this._position = value;
  45270. };
  45271. Object.defineProperty(ShadowLight.prototype, "position", {
  45272. /**
  45273. * Sets the position the shadow will be casted from. Also use as the light position for both
  45274. * point and spot lights.
  45275. */
  45276. get: function () {
  45277. return this._position;
  45278. },
  45279. /**
  45280. * Sets the position the shadow will be casted from. Also use as the light position for both
  45281. * point and spot lights.
  45282. */
  45283. set: function (value) {
  45284. this._setPosition(value);
  45285. },
  45286. enumerable: true,
  45287. configurable: true
  45288. });
  45289. ShadowLight.prototype._setDirection = function (value) {
  45290. this._direction = value;
  45291. };
  45292. Object.defineProperty(ShadowLight.prototype, "direction", {
  45293. /**
  45294. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45295. * Also use as the light direction on spot and directional lights.
  45296. */
  45297. get: function () {
  45298. return this._direction;
  45299. },
  45300. /**
  45301. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45302. * Also use as the light direction on spot and directional lights.
  45303. */
  45304. set: function (value) {
  45305. this._setDirection(value);
  45306. },
  45307. enumerable: true,
  45308. configurable: true
  45309. });
  45310. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45311. /**
  45312. * Gets the shadow projection clipping minimum z value.
  45313. */
  45314. get: function () {
  45315. return this._shadowMinZ;
  45316. },
  45317. /**
  45318. * Sets the shadow projection clipping minimum z value.
  45319. */
  45320. set: function (value) {
  45321. this._shadowMinZ = value;
  45322. this.forceProjectionMatrixCompute();
  45323. },
  45324. enumerable: true,
  45325. configurable: true
  45326. });
  45327. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45328. /**
  45329. * Sets the shadow projection clipping maximum z value.
  45330. */
  45331. get: function () {
  45332. return this._shadowMaxZ;
  45333. },
  45334. /**
  45335. * Gets the shadow projection clipping maximum z value.
  45336. */
  45337. set: function (value) {
  45338. this._shadowMaxZ = value;
  45339. this.forceProjectionMatrixCompute();
  45340. },
  45341. enumerable: true,
  45342. configurable: true
  45343. });
  45344. /**
  45345. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45346. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45347. */
  45348. ShadowLight.prototype.computeTransformedInformation = function () {
  45349. if (this.parent && this.parent.getWorldMatrix) {
  45350. if (!this.transformedPosition) {
  45351. this.transformedPosition = BABYLON.Vector3.Zero();
  45352. }
  45353. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45354. // In case the direction is present.
  45355. if (this.direction) {
  45356. if (!this.transformedDirection) {
  45357. this.transformedDirection = BABYLON.Vector3.Zero();
  45358. }
  45359. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45360. }
  45361. return true;
  45362. }
  45363. return false;
  45364. };
  45365. /**
  45366. * Return the depth scale used for the shadow map.
  45367. * @returns the depth scale.
  45368. */
  45369. ShadowLight.prototype.getDepthScale = function () {
  45370. return 50.0;
  45371. };
  45372. /**
  45373. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45374. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45375. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45376. */
  45377. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45378. return this.transformedDirection ? this.transformedDirection : this.direction;
  45379. };
  45380. /**
  45381. * Returns the ShadowLight absolute position in the World.
  45382. * @returns the position vector in world space
  45383. */
  45384. ShadowLight.prototype.getAbsolutePosition = function () {
  45385. return this.transformedPosition ? this.transformedPosition : this.position;
  45386. };
  45387. /**
  45388. * Sets the ShadowLight direction toward the passed target.
  45389. * @param target The point tot target in local space
  45390. * @returns the updated ShadowLight direction
  45391. */
  45392. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45393. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45394. return this.direction;
  45395. };
  45396. /**
  45397. * Returns the light rotation in euler definition.
  45398. * @returns the x y z rotation in local space.
  45399. */
  45400. ShadowLight.prototype.getRotation = function () {
  45401. this.direction.normalize();
  45402. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45403. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45404. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45405. };
  45406. /**
  45407. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45408. * @returns true if a cube texture needs to be use
  45409. */
  45410. ShadowLight.prototype.needCube = function () {
  45411. return false;
  45412. };
  45413. /**
  45414. * Detects if the projection matrix requires to be recomputed this frame.
  45415. * @returns true if it requires to be recomputed otherwise, false.
  45416. */
  45417. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45418. return this._needProjectionMatrixCompute;
  45419. };
  45420. /**
  45421. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45422. */
  45423. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45424. this._needProjectionMatrixCompute = true;
  45425. };
  45426. /**
  45427. * Get the world matrix of the sahdow lights.
  45428. * @ignore Internal Use Only
  45429. */
  45430. ShadowLight.prototype._getWorldMatrix = function () {
  45431. if (!this._worldMatrix) {
  45432. this._worldMatrix = BABYLON.Matrix.Identity();
  45433. }
  45434. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45435. return this._worldMatrix;
  45436. };
  45437. /**
  45438. * Gets the minZ used for shadow according to both the scene and the light.
  45439. * @param activeCamera The camera we are returning the min for
  45440. * @returns the depth min z
  45441. */
  45442. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45443. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45444. };
  45445. /**
  45446. * Gets the maxZ used for shadow according to both the scene and the light.
  45447. * @param activeCamera The camera we are returning the max for
  45448. * @returns the depth max z
  45449. */
  45450. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45451. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45452. };
  45453. /**
  45454. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45455. * @param matrix The materix to updated with the projection information
  45456. * @param viewMatrix The transform matrix of the light
  45457. * @param renderList The list of mesh to render in the map
  45458. * @returns The current light
  45459. */
  45460. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45461. if (this.customProjectionMatrixBuilder) {
  45462. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45463. }
  45464. else {
  45465. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45466. }
  45467. return this;
  45468. };
  45469. __decorate([
  45470. BABYLON.serializeAsVector3()
  45471. ], ShadowLight.prototype, "position", null);
  45472. __decorate([
  45473. BABYLON.serializeAsVector3()
  45474. ], ShadowLight.prototype, "direction", null);
  45475. __decorate([
  45476. BABYLON.serialize()
  45477. ], ShadowLight.prototype, "shadowMinZ", null);
  45478. __decorate([
  45479. BABYLON.serialize()
  45480. ], ShadowLight.prototype, "shadowMaxZ", null);
  45481. return ShadowLight;
  45482. }(BABYLON.Light));
  45483. BABYLON.ShadowLight = ShadowLight;
  45484. })(BABYLON || (BABYLON = {}));
  45485. //# sourceMappingURL=babylon.shadowLight.js.map
  45486. var BABYLON;
  45487. (function (BABYLON) {
  45488. /**
  45489. * A point light is a light defined by an unique point in world space.
  45490. * The light is emitted in every direction from this point.
  45491. * A good example of a point light is a standard light bulb.
  45492. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45493. */
  45494. var PointLight = /** @class */ (function (_super) {
  45495. __extends(PointLight, _super);
  45496. /**
  45497. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45498. * A PointLight emits the light in every direction.
  45499. * It can cast shadows.
  45500. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45501. * ```javascript
  45502. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45503. * ```
  45504. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45505. * @param name The light friendly name
  45506. * @param position The position of the point light in the scene
  45507. * @param scene The scene the lights belongs to
  45508. */
  45509. function PointLight(name, position, scene) {
  45510. var _this = _super.call(this, name, scene) || this;
  45511. _this._shadowAngle = Math.PI / 2;
  45512. _this.position = position;
  45513. return _this;
  45514. }
  45515. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45516. /**
  45517. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45518. * This specifies what angle the shadow will use to be created.
  45519. *
  45520. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45521. */
  45522. get: function () {
  45523. return this._shadowAngle;
  45524. },
  45525. /**
  45526. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45527. * This specifies what angle the shadow will use to be created.
  45528. *
  45529. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45530. */
  45531. set: function (value) {
  45532. this._shadowAngle = value;
  45533. this.forceProjectionMatrixCompute();
  45534. },
  45535. enumerable: true,
  45536. configurable: true
  45537. });
  45538. Object.defineProperty(PointLight.prototype, "direction", {
  45539. /**
  45540. * Gets the direction if it has been set.
  45541. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45542. */
  45543. get: function () {
  45544. return this._direction;
  45545. },
  45546. /**
  45547. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45548. */
  45549. set: function (value) {
  45550. var previousNeedCube = this.needCube();
  45551. this._direction = value;
  45552. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45553. this._shadowGenerator.recreateShadowMap();
  45554. }
  45555. },
  45556. enumerable: true,
  45557. configurable: true
  45558. });
  45559. /**
  45560. * Returns the string "PointLight"
  45561. * @returns the class name
  45562. */
  45563. PointLight.prototype.getClassName = function () {
  45564. return "PointLight";
  45565. };
  45566. /**
  45567. * Returns the integer 0.
  45568. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45569. */
  45570. PointLight.prototype.getTypeID = function () {
  45571. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45572. };
  45573. /**
  45574. * Specifies wether or not the shadowmap should be a cube texture.
  45575. * @returns true if the shadowmap needs to be a cube texture.
  45576. */
  45577. PointLight.prototype.needCube = function () {
  45578. return !this.direction;
  45579. };
  45580. /**
  45581. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45582. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45583. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45584. */
  45585. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45586. if (this.direction) {
  45587. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45588. }
  45589. else {
  45590. switch (faceIndex) {
  45591. case 0:
  45592. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45593. case 1:
  45594. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45595. case 2:
  45596. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45597. case 3:
  45598. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45599. case 4:
  45600. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45601. case 5:
  45602. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45603. }
  45604. }
  45605. return BABYLON.Vector3.Zero();
  45606. };
  45607. /**
  45608. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45609. * - fov = PI / 2
  45610. * - aspect ratio : 1.0
  45611. * - z-near and far equal to the active camera minZ and maxZ.
  45612. * Returns the PointLight.
  45613. */
  45614. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45615. var activeCamera = this.getScene().activeCamera;
  45616. if (!activeCamera) {
  45617. return;
  45618. }
  45619. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45620. };
  45621. PointLight.prototype._buildUniformLayout = function () {
  45622. this._uniformBuffer.addUniform("vLightData", 4);
  45623. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45624. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45625. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45626. this._uniformBuffer.addUniform("depthValues", 2);
  45627. this._uniformBuffer.create();
  45628. };
  45629. /**
  45630. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45631. * @param effect The effect to update
  45632. * @param lightIndex The index of the light in the effect to update
  45633. * @returns The point light
  45634. */
  45635. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45636. if (this.computeTransformedInformation()) {
  45637. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45638. return this;
  45639. }
  45640. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45641. return this;
  45642. };
  45643. __decorate([
  45644. BABYLON.serialize()
  45645. ], PointLight.prototype, "shadowAngle", null);
  45646. return PointLight;
  45647. }(BABYLON.ShadowLight));
  45648. BABYLON.PointLight = PointLight;
  45649. })(BABYLON || (BABYLON = {}));
  45650. //# sourceMappingURL=babylon.pointLight.js.map
  45651. var BABYLON;
  45652. (function (BABYLON) {
  45653. /**
  45654. * A directional light is defined by a direction (what a surprise!).
  45655. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45656. * 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.
  45657. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45658. */
  45659. var DirectionalLight = /** @class */ (function (_super) {
  45660. __extends(DirectionalLight, _super);
  45661. /**
  45662. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45663. * The directional light is emitted from everywhere in the given direction.
  45664. * It can cast shawdows.
  45665. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45666. * @param name The friendly name of the light
  45667. * @param direction The direction of the light
  45668. * @param scene The scene the light belongs to
  45669. */
  45670. function DirectionalLight(name, direction, scene) {
  45671. var _this = _super.call(this, name, scene) || this;
  45672. _this._shadowFrustumSize = 0;
  45673. _this._shadowOrthoScale = 0.5;
  45674. /**
  45675. * Automatically compute the projection matrix to best fit (including all the casters)
  45676. * on each frame.
  45677. */
  45678. _this.autoUpdateExtends = true;
  45679. // Cache
  45680. _this._orthoLeft = Number.MAX_VALUE;
  45681. _this._orthoRight = Number.MIN_VALUE;
  45682. _this._orthoTop = Number.MIN_VALUE;
  45683. _this._orthoBottom = Number.MAX_VALUE;
  45684. _this.position = direction.scale(-1.0);
  45685. _this.direction = direction;
  45686. return _this;
  45687. }
  45688. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45689. /**
  45690. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45691. */
  45692. get: function () {
  45693. return this._shadowFrustumSize;
  45694. },
  45695. /**
  45696. * Specifies a fix frustum size for the shadow generation.
  45697. */
  45698. set: function (value) {
  45699. this._shadowFrustumSize = value;
  45700. this.forceProjectionMatrixCompute();
  45701. },
  45702. enumerable: true,
  45703. configurable: true
  45704. });
  45705. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45706. /**
  45707. * Gets the shadow projection scale against the optimal computed one.
  45708. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45709. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45710. */
  45711. get: function () {
  45712. return this._shadowOrthoScale;
  45713. },
  45714. /**
  45715. * Sets the shadow projection scale against the optimal computed one.
  45716. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45717. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45718. */
  45719. set: function (value) {
  45720. this._shadowOrthoScale = value;
  45721. this.forceProjectionMatrixCompute();
  45722. },
  45723. enumerable: true,
  45724. configurable: true
  45725. });
  45726. /**
  45727. * Returns the string "DirectionalLight".
  45728. * @return The class name
  45729. */
  45730. DirectionalLight.prototype.getClassName = function () {
  45731. return "DirectionalLight";
  45732. };
  45733. /**
  45734. * Returns the integer 1.
  45735. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45736. */
  45737. DirectionalLight.prototype.getTypeID = function () {
  45738. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45739. };
  45740. /**
  45741. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45742. * Returns the DirectionalLight Shadow projection matrix.
  45743. */
  45744. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45745. if (this.shadowFrustumSize > 0) {
  45746. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45747. }
  45748. else {
  45749. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45750. }
  45751. };
  45752. /**
  45753. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45754. * Returns the DirectionalLight Shadow projection matrix.
  45755. */
  45756. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45757. var activeCamera = this.getScene().activeCamera;
  45758. if (!activeCamera) {
  45759. return;
  45760. }
  45761. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45762. };
  45763. /**
  45764. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45765. * Returns the DirectionalLight Shadow projection matrix.
  45766. */
  45767. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45768. var activeCamera = this.getScene().activeCamera;
  45769. if (!activeCamera) {
  45770. return;
  45771. }
  45772. // Check extends
  45773. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45774. var tempVector3 = BABYLON.Vector3.Zero();
  45775. this._orthoLeft = Number.MAX_VALUE;
  45776. this._orthoRight = Number.MIN_VALUE;
  45777. this._orthoTop = Number.MIN_VALUE;
  45778. this._orthoBottom = Number.MAX_VALUE;
  45779. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45780. var mesh = renderList[meshIndex];
  45781. if (!mesh) {
  45782. continue;
  45783. }
  45784. var boundingInfo = mesh.getBoundingInfo();
  45785. var boundingBox = boundingInfo.boundingBox;
  45786. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45787. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45788. if (tempVector3.x < this._orthoLeft)
  45789. this._orthoLeft = tempVector3.x;
  45790. if (tempVector3.y < this._orthoBottom)
  45791. this._orthoBottom = tempVector3.y;
  45792. if (tempVector3.x > this._orthoRight)
  45793. this._orthoRight = tempVector3.x;
  45794. if (tempVector3.y > this._orthoTop)
  45795. this._orthoTop = tempVector3.y;
  45796. }
  45797. }
  45798. }
  45799. var xOffset = this._orthoRight - this._orthoLeft;
  45800. var yOffset = this._orthoTop - this._orthoBottom;
  45801. 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);
  45802. };
  45803. DirectionalLight.prototype._buildUniformLayout = function () {
  45804. this._uniformBuffer.addUniform("vLightData", 4);
  45805. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45806. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45807. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45808. this._uniformBuffer.addUniform("depthValues", 2);
  45809. this._uniformBuffer.create();
  45810. };
  45811. /**
  45812. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45813. * @param effect The effect to update
  45814. * @param lightIndex The index of the light in the effect to update
  45815. * @returns The directional light
  45816. */
  45817. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45818. if (this.computeTransformedInformation()) {
  45819. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45820. return this;
  45821. }
  45822. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45823. return this;
  45824. };
  45825. /**
  45826. * Gets the minZ used for shadow according to both the scene and the light.
  45827. *
  45828. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45829. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45830. * @param activeCamera The camera we are returning the min for
  45831. * @returns the depth min z
  45832. */
  45833. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45834. return 1;
  45835. };
  45836. /**
  45837. * Gets the maxZ used for shadow according to both the scene and the light.
  45838. *
  45839. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45840. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45841. * @param activeCamera The camera we are returning the max for
  45842. * @returns the depth max z
  45843. */
  45844. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45845. return 1;
  45846. };
  45847. __decorate([
  45848. BABYLON.serialize()
  45849. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45850. __decorate([
  45851. BABYLON.serialize()
  45852. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45853. __decorate([
  45854. BABYLON.serialize()
  45855. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45856. return DirectionalLight;
  45857. }(BABYLON.ShadowLight));
  45858. BABYLON.DirectionalLight = DirectionalLight;
  45859. })(BABYLON || (BABYLON = {}));
  45860. //# sourceMappingURL=babylon.directionalLight.js.map
  45861. var BABYLON;
  45862. (function (BABYLON) {
  45863. /**
  45864. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45865. * These values define a cone of light starting from the position, emitting toward the direction.
  45866. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45867. * and the exponent defines the speed of the decay of the light with distance (reach).
  45868. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45869. */
  45870. var SpotLight = /** @class */ (function (_super) {
  45871. __extends(SpotLight, _super);
  45872. /**
  45873. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45874. * It can cast shadows.
  45875. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45876. * @param name The light friendly name
  45877. * @param position The position of the spot light in the scene
  45878. * @param direction The direction of the light in the scene
  45879. * @param angle The cone angle of the light in Radians
  45880. * @param exponent The light decay speed with the distance from the emission spot
  45881. * @param scene The scene the lights belongs to
  45882. */
  45883. function SpotLight(name, position, direction, angle, exponent, scene) {
  45884. var _this = _super.call(this, name, scene) || this;
  45885. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45886. _this._projectionTextureLightNear = 1e-6;
  45887. _this._projectionTextureLightFar = 1000.0;
  45888. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45889. _this._projectionTextureViewLightDirty = true;
  45890. _this._projectionTextureProjectionLightDirty = true;
  45891. _this._projectionTextureDirty = true;
  45892. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45893. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45894. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45895. _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);
  45896. _this.position = position;
  45897. _this.direction = direction;
  45898. _this.angle = angle;
  45899. _this.exponent = exponent;
  45900. return _this;
  45901. }
  45902. Object.defineProperty(SpotLight.prototype, "angle", {
  45903. /**
  45904. * Gets the cone angle of the spot light in Radians.
  45905. */
  45906. get: function () {
  45907. return this._angle;
  45908. },
  45909. /**
  45910. * Sets the cone angle of the spot light in Radians.
  45911. */
  45912. set: function (value) {
  45913. this._angle = value;
  45914. this._projectionTextureProjectionLightDirty = true;
  45915. this.forceProjectionMatrixCompute();
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45921. /**
  45922. * Allows scaling the angle of the light for shadow generation only.
  45923. */
  45924. get: function () {
  45925. return this._shadowAngleScale;
  45926. },
  45927. /**
  45928. * Allows scaling the angle of the light for shadow generation only.
  45929. */
  45930. set: function (value) {
  45931. this._shadowAngleScale = value;
  45932. this.forceProjectionMatrixCompute();
  45933. },
  45934. enumerable: true,
  45935. configurable: true
  45936. });
  45937. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45938. /**
  45939. * Allows reading the projecton texture
  45940. */
  45941. get: function () {
  45942. return this._projectionTextureMatrix;
  45943. },
  45944. enumerable: true,
  45945. configurable: true
  45946. });
  45947. ;
  45948. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45949. /**
  45950. * Gets the near clip of the Spotlight for texture projection.
  45951. */
  45952. get: function () {
  45953. return this._projectionTextureLightNear;
  45954. },
  45955. /**
  45956. * Sets the near clip of the Spotlight for texture projection.
  45957. */
  45958. set: function (value) {
  45959. this._projectionTextureLightNear = value;
  45960. this._projectionTextureProjectionLightDirty = true;
  45961. },
  45962. enumerable: true,
  45963. configurable: true
  45964. });
  45965. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45966. /**
  45967. * Gets the far clip of the Spotlight for texture projection.
  45968. */
  45969. get: function () {
  45970. return this._projectionTextureLightFar;
  45971. },
  45972. /**
  45973. * Sets the far clip of the Spotlight for texture projection.
  45974. */
  45975. set: function (value) {
  45976. this._projectionTextureLightFar = value;
  45977. this._projectionTextureProjectionLightDirty = true;
  45978. },
  45979. enumerable: true,
  45980. configurable: true
  45981. });
  45982. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45983. /**
  45984. * Gets the Up vector of the Spotlight for texture projection.
  45985. */
  45986. get: function () {
  45987. return this._projectionTextureUpDirection;
  45988. },
  45989. /**
  45990. * Sets the Up vector of the Spotlight for texture projection.
  45991. */
  45992. set: function (value) {
  45993. this._projectionTextureUpDirection = value;
  45994. this._projectionTextureProjectionLightDirty = true;
  45995. },
  45996. enumerable: true,
  45997. configurable: true
  45998. });
  45999. ;
  46000. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46001. /**
  46002. * Gets the projection texture of the light.
  46003. */
  46004. get: function () {
  46005. return this._projectionTexture;
  46006. },
  46007. /**
  46008. * Sets the projection texture of the light.
  46009. */
  46010. set: function (value) {
  46011. this._projectionTexture = value;
  46012. this._projectionTextureDirty = true;
  46013. },
  46014. enumerable: true,
  46015. configurable: true
  46016. });
  46017. /**
  46018. * Returns the string "SpotLight".
  46019. * @returns the class name
  46020. */
  46021. SpotLight.prototype.getClassName = function () {
  46022. return "SpotLight";
  46023. };
  46024. /**
  46025. * Returns the integer 2.
  46026. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46027. */
  46028. SpotLight.prototype.getTypeID = function () {
  46029. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46030. };
  46031. /**
  46032. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46033. */
  46034. SpotLight.prototype._setDirection = function (value) {
  46035. _super.prototype._setDirection.call(this, value);
  46036. this._projectionTextureViewLightDirty = true;
  46037. };
  46038. /**
  46039. * Overrides the position setter to recompute the projection texture view light Matrix.
  46040. */
  46041. SpotLight.prototype._setPosition = function (value) {
  46042. _super.prototype._setPosition.call(this, value);
  46043. this._projectionTextureViewLightDirty = true;
  46044. };
  46045. /**
  46046. * 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.
  46047. * Returns the SpotLight.
  46048. */
  46049. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46050. var activeCamera = this.getScene().activeCamera;
  46051. if (!activeCamera) {
  46052. return;
  46053. }
  46054. this._shadowAngleScale = this._shadowAngleScale || 1;
  46055. var angle = this._shadowAngleScale * this._angle;
  46056. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46057. };
  46058. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46059. this._projectionTextureViewLightDirty = false;
  46060. this._projectionTextureDirty = true;
  46061. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46062. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46063. };
  46064. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46065. this._projectionTextureProjectionLightDirty = false;
  46066. this._projectionTextureDirty = true;
  46067. var light_far = this.projectionTextureLightFar;
  46068. var light_near = this.projectionTextureLightNear;
  46069. var P = light_far / (light_far - light_near);
  46070. var Q = -P * light_near;
  46071. var S = 1.0 / Math.tan(this._angle / 2.0);
  46072. var A = 1.0;
  46073. 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);
  46074. };
  46075. /**
  46076. * Main function for light texture projection matrix computing.
  46077. */
  46078. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46079. this._projectionTextureDirty = false;
  46080. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46081. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46082. };
  46083. SpotLight.prototype._buildUniformLayout = function () {
  46084. this._uniformBuffer.addUniform("vLightData", 4);
  46085. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46086. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46087. this._uniformBuffer.addUniform("vLightDirection", 3);
  46088. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46089. this._uniformBuffer.addUniform("depthValues", 2);
  46090. this._uniformBuffer.create();
  46091. };
  46092. /**
  46093. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46094. * @param effect The effect to update
  46095. * @param lightIndex The index of the light in the effect to update
  46096. * @returns The spot light
  46097. */
  46098. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46099. var normalizeDirection;
  46100. if (this.computeTransformedInformation()) {
  46101. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46102. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46103. }
  46104. else {
  46105. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46106. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46107. }
  46108. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46109. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46110. if (this._projectionTextureViewLightDirty) {
  46111. this._computeProjectionTextureViewLightMatrix();
  46112. }
  46113. if (this._projectionTextureProjectionLightDirty) {
  46114. this._computeProjectionTextureProjectionLightMatrix();
  46115. }
  46116. if (this._projectionTextureDirty) {
  46117. this._computeProjectionTextureMatrix();
  46118. }
  46119. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46120. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46121. }
  46122. return this;
  46123. };
  46124. /**
  46125. * Disposes the light and the associated resources.
  46126. */
  46127. SpotLight.prototype.dispose = function () {
  46128. _super.prototype.dispose.call(this);
  46129. if (this._projectionTexture) {
  46130. this._projectionTexture.dispose();
  46131. }
  46132. };
  46133. __decorate([
  46134. BABYLON.serialize()
  46135. ], SpotLight.prototype, "angle", null);
  46136. __decorate([
  46137. BABYLON.serialize()
  46138. ], SpotLight.prototype, "shadowAngleScale", null);
  46139. __decorate([
  46140. BABYLON.serialize()
  46141. ], SpotLight.prototype, "exponent", void 0);
  46142. __decorate([
  46143. BABYLON.serialize()
  46144. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46145. __decorate([
  46146. BABYLON.serialize()
  46147. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46148. __decorate([
  46149. BABYLON.serialize()
  46150. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46151. __decorate([
  46152. BABYLON.serializeAsTexture("projectedLightTexture")
  46153. ], SpotLight.prototype, "_projectionTexture", void 0);
  46154. return SpotLight;
  46155. }(BABYLON.ShadowLight));
  46156. BABYLON.SpotLight = SpotLight;
  46157. })(BABYLON || (BABYLON = {}));
  46158. //# sourceMappingURL=babylon.spotLight.js.map
  46159. var BABYLON;
  46160. (function (BABYLON) {
  46161. /**
  46162. * Class used to override all child animations of a given target
  46163. */
  46164. var AnimationPropertiesOverride = /** @class */ (function () {
  46165. function AnimationPropertiesOverride() {
  46166. /**
  46167. * Gets or sets a value indicating if animation blending must be used
  46168. */
  46169. this.enableBlending = false;
  46170. /**
  46171. * Gets or sets the blending speed to use when enableBlending is true
  46172. */
  46173. this.blendingSpeed = 0.01;
  46174. /**
  46175. * Gets or sets the default loop mode to use
  46176. */
  46177. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46178. }
  46179. return AnimationPropertiesOverride;
  46180. }());
  46181. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46182. })(BABYLON || (BABYLON = {}));
  46183. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46184. var BABYLON;
  46185. (function (BABYLON) {
  46186. var AnimationRange = /** @class */ (function () {
  46187. function AnimationRange(name, from, to) {
  46188. this.name = name;
  46189. this.from = from;
  46190. this.to = to;
  46191. }
  46192. AnimationRange.prototype.clone = function () {
  46193. return new AnimationRange(this.name, this.from, this.to);
  46194. };
  46195. return AnimationRange;
  46196. }());
  46197. BABYLON.AnimationRange = AnimationRange;
  46198. /**
  46199. * Composed of a frame, and an action function
  46200. */
  46201. var AnimationEvent = /** @class */ (function () {
  46202. function AnimationEvent(frame, action, onlyOnce) {
  46203. this.frame = frame;
  46204. this.action = action;
  46205. this.onlyOnce = onlyOnce;
  46206. this.isDone = false;
  46207. }
  46208. return AnimationEvent;
  46209. }());
  46210. BABYLON.AnimationEvent = AnimationEvent;
  46211. var PathCursor = /** @class */ (function () {
  46212. function PathCursor(path) {
  46213. this.path = path;
  46214. this._onchange = new Array();
  46215. this.value = 0;
  46216. this.animations = new Array();
  46217. }
  46218. PathCursor.prototype.getPoint = function () {
  46219. var point = this.path.getPointAtLengthPosition(this.value);
  46220. return new BABYLON.Vector3(point.x, 0, point.y);
  46221. };
  46222. PathCursor.prototype.moveAhead = function (step) {
  46223. if (step === void 0) { step = 0.002; }
  46224. this.move(step);
  46225. return this;
  46226. };
  46227. PathCursor.prototype.moveBack = function (step) {
  46228. if (step === void 0) { step = 0.002; }
  46229. this.move(-step);
  46230. return this;
  46231. };
  46232. PathCursor.prototype.move = function (step) {
  46233. if (Math.abs(step) > 1) {
  46234. throw "step size should be less than 1.";
  46235. }
  46236. this.value += step;
  46237. this.ensureLimits();
  46238. this.raiseOnChange();
  46239. return this;
  46240. };
  46241. PathCursor.prototype.ensureLimits = function () {
  46242. while (this.value > 1) {
  46243. this.value -= 1;
  46244. }
  46245. while (this.value < 0) {
  46246. this.value += 1;
  46247. }
  46248. return this;
  46249. };
  46250. // used by animation engine
  46251. PathCursor.prototype.raiseOnChange = function () {
  46252. var _this = this;
  46253. this._onchange.forEach(function (f) { return f(_this); });
  46254. return this;
  46255. };
  46256. PathCursor.prototype.onchange = function (f) {
  46257. this._onchange.push(f);
  46258. return this;
  46259. };
  46260. return PathCursor;
  46261. }());
  46262. BABYLON.PathCursor = PathCursor;
  46263. var AnimationKeyInterpolation;
  46264. (function (AnimationKeyInterpolation) {
  46265. /**
  46266. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46267. */
  46268. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46269. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46270. var Animation = /** @class */ (function () {
  46271. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46272. this.name = name;
  46273. this.targetProperty = targetProperty;
  46274. this.framePerSecond = framePerSecond;
  46275. this.dataType = dataType;
  46276. this.loopMode = loopMode;
  46277. this.enableBlending = enableBlending;
  46278. this._runtimeAnimations = new Array();
  46279. // The set of event that will be linked to this animation
  46280. this._events = new Array();
  46281. this.blendingSpeed = 0.01;
  46282. this._ranges = {};
  46283. this.targetPropertyPath = targetProperty.split(".");
  46284. this.dataType = dataType;
  46285. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46286. }
  46287. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46288. var dataType = undefined;
  46289. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46290. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46291. }
  46292. else if (from instanceof BABYLON.Quaternion) {
  46293. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46294. }
  46295. else if (from instanceof BABYLON.Vector3) {
  46296. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46297. }
  46298. else if (from instanceof BABYLON.Vector2) {
  46299. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46300. }
  46301. else if (from instanceof BABYLON.Color3) {
  46302. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46303. }
  46304. else if (from instanceof BABYLON.Size) {
  46305. dataType = Animation.ANIMATIONTYPE_SIZE;
  46306. }
  46307. if (dataType == undefined) {
  46308. return null;
  46309. }
  46310. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46311. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46312. animation.setKeys(keys);
  46313. if (easingFunction !== undefined) {
  46314. animation.setEasingFunction(easingFunction);
  46315. }
  46316. return animation;
  46317. };
  46318. /**
  46319. * Sets up an animation.
  46320. * @param property the property to animate
  46321. * @param animationType the animation type to apply
  46322. * @param easingFunction the easing function used in the animation
  46323. * @returns The created animation
  46324. */
  46325. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46326. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46327. animation.setEasingFunction(easingFunction);
  46328. return animation;
  46329. };
  46330. /**
  46331. * Create and start an animation on a node
  46332. * @param {string} name defines the name of the global animation that will be run on all nodes
  46333. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46334. * @param {string} targetProperty defines property to animate
  46335. * @param {number} framePerSecond defines the number of frame per second yo use
  46336. * @param {number} totalFrame defines the number of frames in total
  46337. * @param {any} from defines the initial value
  46338. * @param {any} to defines the final value
  46339. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46340. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46341. * @param onAnimationEnd defines the callback to call when animation end
  46342. * @returns the animatable created for this animation
  46343. */
  46344. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46345. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46346. if (!animation) {
  46347. return null;
  46348. }
  46349. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46350. };
  46351. /**
  46352. * Create and start an animation on a node and its descendants
  46353. * @param {string} name defines the name of the global animation that will be run on all nodes
  46354. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46355. * @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.
  46356. * @param {string} targetProperty defines property to animate
  46357. * @param {number} framePerSecond defines the number of frame per second yo use
  46358. * @param {number} totalFrame defines the number of frames in total
  46359. * @param {any} from defines the initial value
  46360. * @param {any} to defines the final value
  46361. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46362. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46363. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46364. * @returns the list of animatables created for all nodes
  46365. * @example https://www.babylonjs-playground.com/#MH0VLI
  46366. */
  46367. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46368. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46369. if (!animation) {
  46370. return null;
  46371. }
  46372. var scene = node.getScene();
  46373. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46374. };
  46375. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46376. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46377. if (!animation) {
  46378. return null;
  46379. }
  46380. node.animations.push(animation);
  46381. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46382. };
  46383. /**
  46384. * Transition property of the Camera to the target Value.
  46385. * @param property The property to transition
  46386. * @param targetValue The target Value of the property
  46387. * @param host The object where the property to animate belongs
  46388. * @param scene Scene used to run the animation
  46389. * @param frameRate Framerate (in frame/s) to use
  46390. * @param transition The transition type we want to use
  46391. * @param duration The duration of the animation, in milliseconds
  46392. * @param onAnimationEnd Call back trigger at the end of the animation.
  46393. */
  46394. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46395. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46396. if (duration <= 0) {
  46397. host[property] = targetValue;
  46398. if (onAnimationEnd) {
  46399. onAnimationEnd();
  46400. }
  46401. return null;
  46402. }
  46403. var endFrame = frameRate * (duration / 1000);
  46404. transition.setKeys([{
  46405. frame: 0,
  46406. value: host[property].clone ? host[property].clone() : host[property]
  46407. },
  46408. {
  46409. frame: endFrame,
  46410. value: targetValue
  46411. }]);
  46412. if (!host.animations) {
  46413. host.animations = [];
  46414. }
  46415. host.animations.push(transition);
  46416. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46417. animation.onAnimationEnd = onAnimationEnd;
  46418. return animation;
  46419. };
  46420. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46421. /**
  46422. * Return the array of runtime animations currently using this animation
  46423. */
  46424. get: function () {
  46425. return this._runtimeAnimations;
  46426. },
  46427. enumerable: true,
  46428. configurable: true
  46429. });
  46430. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46431. get: function () {
  46432. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46433. var runtimeAnimation = _a[_i];
  46434. if (!runtimeAnimation.isStopped) {
  46435. return true;
  46436. }
  46437. }
  46438. return false;
  46439. },
  46440. enumerable: true,
  46441. configurable: true
  46442. });
  46443. // Methods
  46444. /**
  46445. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46446. */
  46447. Animation.prototype.toString = function (fullDetails) {
  46448. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46449. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46450. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46451. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46452. if (fullDetails) {
  46453. ret += ", Ranges: {";
  46454. var first = true;
  46455. for (var name in this._ranges) {
  46456. if (first) {
  46457. ret += ", ";
  46458. first = false;
  46459. }
  46460. ret += name;
  46461. }
  46462. ret += "}";
  46463. }
  46464. return ret;
  46465. };
  46466. /**
  46467. * Add an event to this animation.
  46468. */
  46469. Animation.prototype.addEvent = function (event) {
  46470. this._events.push(event);
  46471. };
  46472. /**
  46473. * Remove all events found at the given frame
  46474. * @param frame
  46475. */
  46476. Animation.prototype.removeEvents = function (frame) {
  46477. for (var index = 0; index < this._events.length; index++) {
  46478. if (this._events[index].frame === frame) {
  46479. this._events.splice(index, 1);
  46480. index--;
  46481. }
  46482. }
  46483. };
  46484. Animation.prototype.getEvents = function () {
  46485. return this._events;
  46486. };
  46487. Animation.prototype.createRange = function (name, from, to) {
  46488. // check name not already in use; could happen for bones after serialized
  46489. if (!this._ranges[name]) {
  46490. this._ranges[name] = new AnimationRange(name, from, to);
  46491. }
  46492. };
  46493. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46494. if (deleteFrames === void 0) { deleteFrames = true; }
  46495. var range = this._ranges[name];
  46496. if (!range) {
  46497. return;
  46498. }
  46499. if (deleteFrames) {
  46500. var from = range.from;
  46501. var to = range.to;
  46502. // this loop MUST go high to low for multiple splices to work
  46503. for (var key = this._keys.length - 1; key >= 0; key--) {
  46504. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46505. this._keys.splice(key, 1);
  46506. }
  46507. }
  46508. }
  46509. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46510. };
  46511. Animation.prototype.getRange = function (name) {
  46512. return this._ranges[name];
  46513. };
  46514. Animation.prototype.getKeys = function () {
  46515. return this._keys;
  46516. };
  46517. Animation.prototype.getHighestFrame = function () {
  46518. var ret = 0;
  46519. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46520. if (ret < this._keys[key].frame) {
  46521. ret = this._keys[key].frame;
  46522. }
  46523. }
  46524. return ret;
  46525. };
  46526. Animation.prototype.getEasingFunction = function () {
  46527. return this._easingFunction;
  46528. };
  46529. Animation.prototype.setEasingFunction = function (easingFunction) {
  46530. this._easingFunction = easingFunction;
  46531. };
  46532. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46533. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46534. };
  46535. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46536. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46537. };
  46538. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46539. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46540. };
  46541. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46542. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46543. };
  46544. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46545. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46546. };
  46547. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46548. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46549. };
  46550. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46551. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46552. };
  46553. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46554. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46555. };
  46556. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46557. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46558. };
  46559. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46560. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46561. };
  46562. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46563. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46564. };
  46565. Animation.prototype.clone = function () {
  46566. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46567. clone.enableBlending = this.enableBlending;
  46568. clone.blendingSpeed = this.blendingSpeed;
  46569. if (this._keys) {
  46570. clone.setKeys(this._keys);
  46571. }
  46572. if (this._ranges) {
  46573. clone._ranges = {};
  46574. for (var name in this._ranges) {
  46575. var range = this._ranges[name];
  46576. if (!range) {
  46577. continue;
  46578. }
  46579. clone._ranges[name] = range.clone();
  46580. }
  46581. }
  46582. return clone;
  46583. };
  46584. Animation.prototype.setKeys = function (values) {
  46585. this._keys = values.slice(0);
  46586. };
  46587. Animation.prototype.serialize = function () {
  46588. var serializationObject = {};
  46589. serializationObject.name = this.name;
  46590. serializationObject.property = this.targetProperty;
  46591. serializationObject.framePerSecond = this.framePerSecond;
  46592. serializationObject.dataType = this.dataType;
  46593. serializationObject.loopBehavior = this.loopMode;
  46594. serializationObject.enableBlending = this.enableBlending;
  46595. serializationObject.blendingSpeed = this.blendingSpeed;
  46596. var dataType = this.dataType;
  46597. serializationObject.keys = [];
  46598. var keys = this.getKeys();
  46599. for (var index = 0; index < keys.length; index++) {
  46600. var animationKey = keys[index];
  46601. var key = {};
  46602. key.frame = animationKey.frame;
  46603. switch (dataType) {
  46604. case Animation.ANIMATIONTYPE_FLOAT:
  46605. key.values = [animationKey.value];
  46606. break;
  46607. case Animation.ANIMATIONTYPE_QUATERNION:
  46608. case Animation.ANIMATIONTYPE_MATRIX:
  46609. case Animation.ANIMATIONTYPE_VECTOR3:
  46610. case Animation.ANIMATIONTYPE_COLOR3:
  46611. key.values = animationKey.value.asArray();
  46612. break;
  46613. }
  46614. serializationObject.keys.push(key);
  46615. }
  46616. serializationObject.ranges = [];
  46617. for (var name in this._ranges) {
  46618. var source = this._ranges[name];
  46619. if (!source) {
  46620. continue;
  46621. }
  46622. var range = {};
  46623. range.name = name;
  46624. range.from = source.from;
  46625. range.to = source.to;
  46626. serializationObject.ranges.push(range);
  46627. }
  46628. return serializationObject;
  46629. };
  46630. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46631. get: function () {
  46632. return Animation._ANIMATIONTYPE_FLOAT;
  46633. },
  46634. enumerable: true,
  46635. configurable: true
  46636. });
  46637. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46638. get: function () {
  46639. return Animation._ANIMATIONTYPE_VECTOR3;
  46640. },
  46641. enumerable: true,
  46642. configurable: true
  46643. });
  46644. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46645. get: function () {
  46646. return Animation._ANIMATIONTYPE_VECTOR2;
  46647. },
  46648. enumerable: true,
  46649. configurable: true
  46650. });
  46651. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46652. get: function () {
  46653. return Animation._ANIMATIONTYPE_SIZE;
  46654. },
  46655. enumerable: true,
  46656. configurable: true
  46657. });
  46658. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46659. get: function () {
  46660. return Animation._ANIMATIONTYPE_QUATERNION;
  46661. },
  46662. enumerable: true,
  46663. configurable: true
  46664. });
  46665. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46666. get: function () {
  46667. return Animation._ANIMATIONTYPE_MATRIX;
  46668. },
  46669. enumerable: true,
  46670. configurable: true
  46671. });
  46672. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46673. get: function () {
  46674. return Animation._ANIMATIONTYPE_COLOR3;
  46675. },
  46676. enumerable: true,
  46677. configurable: true
  46678. });
  46679. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46680. get: function () {
  46681. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46682. },
  46683. enumerable: true,
  46684. configurable: true
  46685. });
  46686. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46687. get: function () {
  46688. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46689. },
  46690. enumerable: true,
  46691. configurable: true
  46692. });
  46693. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46694. get: function () {
  46695. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46696. },
  46697. enumerable: true,
  46698. configurable: true
  46699. });
  46700. Animation.Parse = function (parsedAnimation) {
  46701. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46702. var dataType = parsedAnimation.dataType;
  46703. var keys = [];
  46704. var data;
  46705. var index;
  46706. if (parsedAnimation.enableBlending) {
  46707. animation.enableBlending = parsedAnimation.enableBlending;
  46708. }
  46709. if (parsedAnimation.blendingSpeed) {
  46710. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46711. }
  46712. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46713. var key = parsedAnimation.keys[index];
  46714. var inTangent;
  46715. var outTangent;
  46716. switch (dataType) {
  46717. case Animation.ANIMATIONTYPE_FLOAT:
  46718. data = key.values[0];
  46719. if (key.values.length >= 1) {
  46720. inTangent = key.values[1];
  46721. }
  46722. if (key.values.length >= 2) {
  46723. outTangent = key.values[2];
  46724. }
  46725. break;
  46726. case Animation.ANIMATIONTYPE_QUATERNION:
  46727. data = BABYLON.Quaternion.FromArray(key.values);
  46728. if (key.values.length >= 8) {
  46729. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46730. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46731. inTangent = _inTangent;
  46732. }
  46733. }
  46734. if (key.values.length >= 12) {
  46735. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46736. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46737. outTangent = _outTangent;
  46738. }
  46739. }
  46740. break;
  46741. case Animation.ANIMATIONTYPE_MATRIX:
  46742. data = BABYLON.Matrix.FromArray(key.values);
  46743. break;
  46744. case Animation.ANIMATIONTYPE_COLOR3:
  46745. data = BABYLON.Color3.FromArray(key.values);
  46746. break;
  46747. case Animation.ANIMATIONTYPE_VECTOR3:
  46748. default:
  46749. data = BABYLON.Vector3.FromArray(key.values);
  46750. break;
  46751. }
  46752. var keyData = {};
  46753. keyData.frame = key.frame;
  46754. keyData.value = data;
  46755. if (inTangent != undefined) {
  46756. keyData.inTangent = inTangent;
  46757. }
  46758. if (outTangent != undefined) {
  46759. keyData.outTangent = outTangent;
  46760. }
  46761. keys.push(keyData);
  46762. }
  46763. animation.setKeys(keys);
  46764. if (parsedAnimation.ranges) {
  46765. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46766. data = parsedAnimation.ranges[index];
  46767. animation.createRange(data.name, data.from, data.to);
  46768. }
  46769. }
  46770. return animation;
  46771. };
  46772. Animation.AppendSerializedAnimations = function (source, destination) {
  46773. if (source.animations) {
  46774. destination.animations = [];
  46775. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46776. var animation = source.animations[animationIndex];
  46777. destination.animations.push(animation.serialize());
  46778. }
  46779. }
  46780. };
  46781. Animation.AllowMatricesInterpolation = false;
  46782. // Statics
  46783. Animation._ANIMATIONTYPE_FLOAT = 0;
  46784. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46785. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46786. Animation._ANIMATIONTYPE_MATRIX = 3;
  46787. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46788. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46789. Animation._ANIMATIONTYPE_SIZE = 6;
  46790. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46791. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46792. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46793. return Animation;
  46794. }());
  46795. BABYLON.Animation = Animation;
  46796. })(BABYLON || (BABYLON = {}));
  46797. //# sourceMappingURL=babylon.animation.js.map
  46798. var BABYLON;
  46799. (function (BABYLON) {
  46800. /**
  46801. * This class defines the direct association between an animation and a target
  46802. */
  46803. var TargetedAnimation = /** @class */ (function () {
  46804. function TargetedAnimation() {
  46805. }
  46806. return TargetedAnimation;
  46807. }());
  46808. BABYLON.TargetedAnimation = TargetedAnimation;
  46809. /**
  46810. * Use this class to create coordinated animations on multiple targets
  46811. */
  46812. var AnimationGroup = /** @class */ (function () {
  46813. function AnimationGroup(name, scene) {
  46814. if (scene === void 0) { scene = null; }
  46815. this.name = name;
  46816. this._targetedAnimations = new Array();
  46817. this._animatables = new Array();
  46818. this._from = Number.MAX_VALUE;
  46819. this._to = -Number.MAX_VALUE;
  46820. this._speedRatio = 1;
  46821. this.onAnimationEndObservable = new BABYLON.Observable();
  46822. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46823. this._scene.animationGroups.push(this);
  46824. }
  46825. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46826. /**
  46827. * Define if the animations are started
  46828. */
  46829. get: function () {
  46830. return this._isStarted;
  46831. },
  46832. enumerable: true,
  46833. configurable: true
  46834. });
  46835. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46836. /**
  46837. * Gets or sets the speed ratio to use for all animations
  46838. */
  46839. get: function () {
  46840. return this._speedRatio;
  46841. },
  46842. /**
  46843. * Gets or sets the speed ratio to use for all animations
  46844. */
  46845. set: function (value) {
  46846. if (this._speedRatio === value) {
  46847. return;
  46848. }
  46849. this._speedRatio = value;
  46850. for (var index = 0; index < this._animatables.length; index++) {
  46851. var animatable = this._animatables[index];
  46852. animatable.speedRatio = this._speedRatio;
  46853. }
  46854. },
  46855. enumerable: true,
  46856. configurable: true
  46857. });
  46858. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46859. /**
  46860. * Gets the targeted animations for this animation group
  46861. */
  46862. get: function () {
  46863. return this._targetedAnimations;
  46864. },
  46865. enumerable: true,
  46866. configurable: true
  46867. });
  46868. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46869. /**
  46870. * returning the list of animatables controlled by this animation group.
  46871. */
  46872. get: function () {
  46873. return this._animatables;
  46874. },
  46875. enumerable: true,
  46876. configurable: true
  46877. });
  46878. /**
  46879. * Add an animation (with its target) in the group
  46880. * @param animation defines the animation we want to add
  46881. * @param target defines the target of the animation
  46882. * @returns the {BABYLON.TargetedAnimation} object
  46883. */
  46884. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46885. var targetedAnimation = {
  46886. animation: animation,
  46887. target: target
  46888. };
  46889. var keys = animation.getKeys();
  46890. if (this._from > keys[0].frame) {
  46891. this._from = keys[0].frame;
  46892. }
  46893. if (this._to < keys[keys.length - 1].frame) {
  46894. this._to = keys[keys.length - 1].frame;
  46895. }
  46896. this._targetedAnimations.push(targetedAnimation);
  46897. return targetedAnimation;
  46898. };
  46899. /**
  46900. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46901. * It can add constant keys at begin or end
  46902. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46903. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46904. */
  46905. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46906. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46907. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46908. beginFrame = Math.max(beginFrame, this._from);
  46909. endFrame = Math.min(endFrame, this._to);
  46910. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46911. var targetedAnimation = this._targetedAnimations[index];
  46912. var keys = targetedAnimation.animation.getKeys();
  46913. var startKey = keys[0];
  46914. var endKey = keys[keys.length - 1];
  46915. if (startKey.frame > beginFrame) {
  46916. var newKey = {
  46917. frame: beginFrame,
  46918. value: startKey.value,
  46919. inTangent: startKey.inTangent,
  46920. outTangent: startKey.outTangent,
  46921. interpolation: startKey.interpolation
  46922. };
  46923. keys.splice(0, 0, newKey);
  46924. }
  46925. if (endKey.frame < endFrame) {
  46926. var newKey = {
  46927. frame: endFrame,
  46928. value: endKey.value,
  46929. inTangent: endKey.outTangent,
  46930. outTangent: endKey.outTangent,
  46931. interpolation: endKey.interpolation
  46932. };
  46933. keys.push(newKey);
  46934. }
  46935. }
  46936. return this;
  46937. };
  46938. /**
  46939. * Start all animations on given targets
  46940. * @param loop defines if animations must loop
  46941. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46942. */
  46943. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46944. var _this = this;
  46945. if (loop === void 0) { loop = false; }
  46946. if (speedRatio === void 0) { speedRatio = 1; }
  46947. if (this._isStarted || this._targetedAnimations.length === 0) {
  46948. return this;
  46949. }
  46950. var _loop_1 = function () {
  46951. var targetedAnimation = this_1._targetedAnimations[index];
  46952. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46953. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46954. }));
  46955. };
  46956. var this_1 = this;
  46957. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46958. _loop_1();
  46959. }
  46960. this._speedRatio = speedRatio;
  46961. this._isStarted = true;
  46962. return this;
  46963. };
  46964. /**
  46965. * Pause all animations
  46966. */
  46967. AnimationGroup.prototype.pause = function () {
  46968. if (!this._isStarted) {
  46969. return this;
  46970. }
  46971. for (var index = 0; index < this._animatables.length; index++) {
  46972. var animatable = this._animatables[index];
  46973. animatable.pause();
  46974. }
  46975. return this;
  46976. };
  46977. /**
  46978. * Play all animations to initial state
  46979. * This function will start() the animations if they were not started or will restart() them if they were paused
  46980. * @param loop defines if animations must loop
  46981. */
  46982. AnimationGroup.prototype.play = function (loop) {
  46983. if (this.isStarted) {
  46984. if (loop !== undefined) {
  46985. for (var index = 0; index < this._animatables.length; index++) {
  46986. var animatable = this._animatables[index];
  46987. animatable.loopAnimation = loop;
  46988. }
  46989. }
  46990. this.restart();
  46991. }
  46992. else {
  46993. this.start(loop, this._speedRatio);
  46994. }
  46995. return this;
  46996. };
  46997. /**
  46998. * Reset all animations to initial state
  46999. */
  47000. AnimationGroup.prototype.reset = function () {
  47001. if (!this._isStarted) {
  47002. return this;
  47003. }
  47004. for (var index = 0; index < this._animatables.length; index++) {
  47005. var animatable = this._animatables[index];
  47006. animatable.reset();
  47007. }
  47008. return this;
  47009. };
  47010. /**
  47011. * Restart animations from key 0
  47012. */
  47013. AnimationGroup.prototype.restart = 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.restart();
  47020. }
  47021. return this;
  47022. };
  47023. /**
  47024. * Stop all animations
  47025. */
  47026. AnimationGroup.prototype.stop = function () {
  47027. if (!this._isStarted) {
  47028. return this;
  47029. }
  47030. for (var index = 0; index < this._animatables.length; index++) {
  47031. var animatable = this._animatables[index];
  47032. animatable.stop();
  47033. }
  47034. this._isStarted = false;
  47035. return this;
  47036. };
  47037. /**
  47038. * Goes to a specific frame in this animation group
  47039. *
  47040. * @param frame the frame number to go to
  47041. * @return the animationGroup
  47042. */
  47043. AnimationGroup.prototype.goToFrame = function (frame) {
  47044. if (!this._isStarted) {
  47045. return this;
  47046. }
  47047. for (var index = 0; index < this._animatables.length; index++) {
  47048. var animatable = this._animatables[index];
  47049. animatable.goToFrame(frame);
  47050. }
  47051. return this;
  47052. };
  47053. /**
  47054. * Dispose all associated resources
  47055. */
  47056. AnimationGroup.prototype.dispose = function () {
  47057. this._targetedAnimations = [];
  47058. this._animatables = [];
  47059. var index = this._scene.animationGroups.indexOf(this);
  47060. if (index > -1) {
  47061. this._scene.animationGroups.splice(index, 1);
  47062. }
  47063. };
  47064. return AnimationGroup;
  47065. }());
  47066. BABYLON.AnimationGroup = AnimationGroup;
  47067. })(BABYLON || (BABYLON = {}));
  47068. //# sourceMappingURL=babylon.animationGroup.js.map
  47069. var BABYLON;
  47070. (function (BABYLON) {
  47071. var RuntimeAnimation = /** @class */ (function () {
  47072. function RuntimeAnimation(target, animation) {
  47073. this._offsetsCache = {};
  47074. this._highLimitsCache = {};
  47075. this._stopped = false;
  47076. this._blendingFactor = 0;
  47077. this._ratioOffset = 0;
  47078. this._animation = animation;
  47079. this._target = target;
  47080. animation._runtimeAnimations.push(this);
  47081. }
  47082. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47083. get: function () {
  47084. return this._animation;
  47085. },
  47086. enumerable: true,
  47087. configurable: true
  47088. });
  47089. RuntimeAnimation.prototype.reset = function () {
  47090. this._offsetsCache = {};
  47091. this._highLimitsCache = {};
  47092. this.currentFrame = 0;
  47093. this._blendingFactor = 0;
  47094. this._originalBlendValue = null;
  47095. };
  47096. RuntimeAnimation.prototype.isStopped = function () {
  47097. return this._stopped;
  47098. };
  47099. RuntimeAnimation.prototype.dispose = function () {
  47100. var index = this._animation.runtimeAnimations.indexOf(this);
  47101. if (index > -1) {
  47102. this._animation.runtimeAnimations.splice(index, 1);
  47103. }
  47104. };
  47105. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47106. if (typeof value === "function") {
  47107. return value();
  47108. }
  47109. return value;
  47110. };
  47111. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47112. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47113. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47114. }
  47115. this.currentFrame = currentFrame;
  47116. var keys = this._animation.getKeys();
  47117. // Try to get a hash to find the right key
  47118. 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));
  47119. if (keys[startKeyIndex].frame >= currentFrame) {
  47120. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47121. startKeyIndex--;
  47122. }
  47123. }
  47124. for (var key = startKeyIndex; key < keys.length; key++) {
  47125. var endKey = keys[key + 1];
  47126. if (endKey.frame >= currentFrame) {
  47127. var startKey = keys[key];
  47128. var startValue = this._getKeyValue(startKey.value);
  47129. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47130. return startValue;
  47131. }
  47132. var endValue = this._getKeyValue(endKey.value);
  47133. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47134. var frameDelta = endKey.frame - startKey.frame;
  47135. // gradient : percent of currentFrame between the frame inf and the frame sup
  47136. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47137. // check for easingFunction and correction of gradient
  47138. var easingFunction = this._animation.getEasingFunction();
  47139. if (easingFunction != null) {
  47140. gradient = easingFunction.ease(gradient);
  47141. }
  47142. switch (this._animation.dataType) {
  47143. // Float
  47144. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47145. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47146. switch (loopMode) {
  47147. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47148. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47149. return floatValue;
  47150. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47151. return offsetValue * repeatCount + floatValue;
  47152. }
  47153. break;
  47154. // Quaternion
  47155. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47156. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47157. switch (loopMode) {
  47158. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47159. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47160. return quatValue;
  47161. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47162. return quatValue.add(offsetValue.scale(repeatCount));
  47163. }
  47164. return quatValue;
  47165. // Vector3
  47166. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47167. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47168. switch (loopMode) {
  47169. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47170. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47171. return vec3Value;
  47172. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47173. return vec3Value.add(offsetValue.scale(repeatCount));
  47174. }
  47175. // Vector2
  47176. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47177. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47178. switch (loopMode) {
  47179. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47180. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47181. return vec2Value;
  47182. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47183. return vec2Value.add(offsetValue.scale(repeatCount));
  47184. }
  47185. // Size
  47186. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47187. switch (loopMode) {
  47188. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47189. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47190. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47191. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47192. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47193. }
  47194. // Color3
  47195. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47196. switch (loopMode) {
  47197. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47198. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47199. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47200. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47201. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47202. }
  47203. // Matrix
  47204. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47205. switch (loopMode) {
  47206. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47207. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47208. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47209. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47210. }
  47211. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47212. return startValue;
  47213. }
  47214. default:
  47215. break;
  47216. }
  47217. break;
  47218. }
  47219. }
  47220. return this._getKeyValue(keys[keys.length - 1].value);
  47221. };
  47222. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47223. if (blend === void 0) { blend = false; }
  47224. // Set value
  47225. var path;
  47226. var destination;
  47227. var targetPropertyPath = this._animation.targetPropertyPath;
  47228. if (targetPropertyPath.length > 1) {
  47229. var property = this._target[targetPropertyPath[0]];
  47230. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47231. property = property[targetPropertyPath[index]];
  47232. }
  47233. path = targetPropertyPath[targetPropertyPath.length - 1];
  47234. destination = property;
  47235. }
  47236. else {
  47237. path = targetPropertyPath[0];
  47238. destination = this._target;
  47239. }
  47240. // Blending
  47241. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47242. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47243. if (enableBlending && this._blendingFactor <= 1.0) {
  47244. if (!this._originalBlendValue) {
  47245. if (destination[path].clone) {
  47246. this._originalBlendValue = destination[path].clone();
  47247. }
  47248. else {
  47249. this._originalBlendValue = destination[path];
  47250. }
  47251. }
  47252. if (this._originalBlendValue.prototype) {
  47253. if (this._originalBlendValue.prototype.Lerp) {
  47254. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47255. }
  47256. else {
  47257. destination[path] = currentValue;
  47258. }
  47259. }
  47260. else if (this._originalBlendValue.m) {
  47261. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47262. }
  47263. else {
  47264. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47265. }
  47266. this._blendingFactor += blendingSpeed;
  47267. }
  47268. else {
  47269. destination[path] = currentValue;
  47270. }
  47271. if (this._target.markAsDirty) {
  47272. this._target.markAsDirty(this._animation.targetProperty);
  47273. }
  47274. };
  47275. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47276. if (this._target && this._target.animationPropertiesOverride) {
  47277. return this._target.animationPropertiesOverride.loopMode;
  47278. }
  47279. return this._animation.loopMode;
  47280. };
  47281. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47282. var keys = this._animation.getKeys();
  47283. if (frame < keys[0].frame) {
  47284. frame = keys[0].frame;
  47285. }
  47286. else if (frame > keys[keys.length - 1].frame) {
  47287. frame = keys[keys.length - 1].frame;
  47288. }
  47289. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47290. this.setValue(currentValue);
  47291. };
  47292. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47293. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47294. this._ratioOffset = this._previousRatio - newRatio;
  47295. };
  47296. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47297. if (blend === void 0) { blend = false; }
  47298. var targetPropertyPath = this._animation.targetPropertyPath;
  47299. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47300. this._stopped = true;
  47301. return false;
  47302. }
  47303. var returnValue = true;
  47304. var keys = this._animation.getKeys();
  47305. // Adding a start key at frame 0 if missing
  47306. if (keys[0].frame !== 0) {
  47307. var newKey = { frame: 0, value: keys[0].value };
  47308. keys.splice(0, 0, newKey);
  47309. }
  47310. // Check limits
  47311. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47312. from = keys[0].frame;
  47313. }
  47314. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47315. to = keys[keys.length - 1].frame;
  47316. }
  47317. //to and from cannot be the same key
  47318. if (from === to) {
  47319. if (from > keys[0].frame) {
  47320. from--;
  47321. }
  47322. else if (to < keys[keys.length - 1].frame) {
  47323. to++;
  47324. }
  47325. }
  47326. // Compute ratio
  47327. var range = to - from;
  47328. var offsetValue;
  47329. // ratio represents the frame delta between from and to
  47330. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47331. var highLimitValue = 0;
  47332. this._previousDelay = delay;
  47333. this._previousRatio = ratio;
  47334. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47335. returnValue = false;
  47336. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47337. }
  47338. else {
  47339. // Get max value if required
  47340. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47341. var keyOffset = to.toString() + from.toString();
  47342. if (!this._offsetsCache[keyOffset]) {
  47343. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47344. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47345. switch (this._animation.dataType) {
  47346. // Float
  47347. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47348. this._offsetsCache[keyOffset] = toValue - fromValue;
  47349. break;
  47350. // Quaternion
  47351. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47352. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47353. break;
  47354. // Vector3
  47355. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47356. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47357. // Vector2
  47358. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47359. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47360. // Size
  47361. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47362. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47363. // Color3
  47364. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47365. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47366. default:
  47367. break;
  47368. }
  47369. this._highLimitsCache[keyOffset] = toValue;
  47370. }
  47371. highLimitValue = this._highLimitsCache[keyOffset];
  47372. offsetValue = this._offsetsCache[keyOffset];
  47373. }
  47374. }
  47375. if (offsetValue === undefined) {
  47376. switch (this._animation.dataType) {
  47377. // Float
  47378. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47379. offsetValue = 0;
  47380. break;
  47381. // Quaternion
  47382. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47383. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47384. break;
  47385. // Vector3
  47386. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47387. offsetValue = BABYLON.Vector3.Zero();
  47388. break;
  47389. // Vector2
  47390. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47391. offsetValue = BABYLON.Vector2.Zero();
  47392. break;
  47393. // Size
  47394. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47395. offsetValue = BABYLON.Size.Zero();
  47396. break;
  47397. // Color3
  47398. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47399. offsetValue = BABYLON.Color3.Black();
  47400. }
  47401. }
  47402. // Compute value
  47403. var repeatCount = (ratio / range) >> 0;
  47404. var currentFrame = returnValue ? from + ratio % range : to;
  47405. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47406. // Set value
  47407. this.setValue(currentValue);
  47408. // Check events
  47409. var events = this._animation.getEvents();
  47410. for (var index = 0; index < events.length; index++) {
  47411. // Make sure current frame has passed event frame and that event frame is within the current range
  47412. // Also, handle both forward and reverse animations
  47413. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47414. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47415. var event = events[index];
  47416. if (!event.isDone) {
  47417. // If event should be done only once, remove it.
  47418. if (event.onlyOnce) {
  47419. events.splice(index, 1);
  47420. index--;
  47421. }
  47422. event.isDone = true;
  47423. event.action();
  47424. } // Don't do anything if the event has already be done.
  47425. }
  47426. else if (events[index].isDone && !events[index].onlyOnce) {
  47427. // reset event, the animation is looping
  47428. events[index].isDone = false;
  47429. }
  47430. }
  47431. if (!returnValue) {
  47432. this._stopped = true;
  47433. }
  47434. return returnValue;
  47435. };
  47436. return RuntimeAnimation;
  47437. }());
  47438. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47439. })(BABYLON || (BABYLON = {}));
  47440. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47441. var BABYLON;
  47442. (function (BABYLON) {
  47443. var Animatable = /** @class */ (function () {
  47444. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47445. if (fromFrame === void 0) { fromFrame = 0; }
  47446. if (toFrame === void 0) { toFrame = 100; }
  47447. if (loopAnimation === void 0) { loopAnimation = false; }
  47448. if (speedRatio === void 0) { speedRatio = 1.0; }
  47449. this.target = target;
  47450. this.fromFrame = fromFrame;
  47451. this.toFrame = toFrame;
  47452. this.loopAnimation = loopAnimation;
  47453. this.onAnimationEnd = onAnimationEnd;
  47454. this._localDelayOffset = null;
  47455. this._pausedDelay = null;
  47456. this._runtimeAnimations = new Array();
  47457. this._paused = false;
  47458. this._speedRatio = 1;
  47459. this.animationStarted = false;
  47460. if (animations) {
  47461. this.appendAnimations(target, animations);
  47462. }
  47463. this._speedRatio = speedRatio;
  47464. this._scene = scene;
  47465. scene._activeAnimatables.push(this);
  47466. }
  47467. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47468. get: function () {
  47469. return this._speedRatio;
  47470. },
  47471. set: function (value) {
  47472. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47473. var animation = this._runtimeAnimations[index];
  47474. animation._prepareForSpeedRatioChange(value);
  47475. }
  47476. this._speedRatio = value;
  47477. },
  47478. enumerable: true,
  47479. configurable: true
  47480. });
  47481. // Methods
  47482. Animatable.prototype.getAnimations = function () {
  47483. return this._runtimeAnimations;
  47484. };
  47485. Animatable.prototype.appendAnimations = function (target, animations) {
  47486. for (var index = 0; index < animations.length; index++) {
  47487. var animation = animations[index];
  47488. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47489. }
  47490. };
  47491. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47492. var runtimeAnimations = this._runtimeAnimations;
  47493. for (var index = 0; index < runtimeAnimations.length; index++) {
  47494. if (runtimeAnimations[index].animation.targetProperty === property) {
  47495. return runtimeAnimations[index].animation;
  47496. }
  47497. }
  47498. return null;
  47499. };
  47500. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47501. var runtimeAnimations = this._runtimeAnimations;
  47502. for (var index = 0; index < runtimeAnimations.length; index++) {
  47503. if (runtimeAnimations[index].animation.targetProperty === property) {
  47504. return runtimeAnimations[index];
  47505. }
  47506. }
  47507. return null;
  47508. };
  47509. Animatable.prototype.reset = function () {
  47510. var runtimeAnimations = this._runtimeAnimations;
  47511. for (var index = 0; index < runtimeAnimations.length; index++) {
  47512. runtimeAnimations[index].reset();
  47513. }
  47514. // Reset to original value
  47515. for (index = 0; index < runtimeAnimations.length; index++) {
  47516. var animation = runtimeAnimations[index];
  47517. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47518. }
  47519. this._localDelayOffset = null;
  47520. this._pausedDelay = null;
  47521. };
  47522. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47523. var runtimeAnimations = this._runtimeAnimations;
  47524. for (var index = 0; index < runtimeAnimations.length; index++) {
  47525. runtimeAnimations[index].animation.enableBlending = true;
  47526. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47527. }
  47528. };
  47529. Animatable.prototype.disableBlending = function () {
  47530. var runtimeAnimations = this._runtimeAnimations;
  47531. for (var index = 0; index < runtimeAnimations.length; index++) {
  47532. runtimeAnimations[index].animation.enableBlending = false;
  47533. }
  47534. };
  47535. Animatable.prototype.goToFrame = function (frame) {
  47536. var runtimeAnimations = this._runtimeAnimations;
  47537. if (runtimeAnimations[0]) {
  47538. var fps = runtimeAnimations[0].animation.framePerSecond;
  47539. var currentFrame = runtimeAnimations[0].currentFrame;
  47540. var adjustTime = frame - currentFrame;
  47541. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47542. if (this._localDelayOffset === null) {
  47543. this._localDelayOffset = 0;
  47544. }
  47545. this._localDelayOffset -= delay;
  47546. }
  47547. for (var index = 0; index < runtimeAnimations.length; index++) {
  47548. runtimeAnimations[index].goToFrame(frame);
  47549. }
  47550. };
  47551. Animatable.prototype.pause = function () {
  47552. if (this._paused) {
  47553. return;
  47554. }
  47555. this._paused = true;
  47556. };
  47557. Animatable.prototype.restart = function () {
  47558. this._paused = false;
  47559. };
  47560. Animatable.prototype.stop = function (animationName) {
  47561. if (animationName) {
  47562. var idx = this._scene._activeAnimatables.indexOf(this);
  47563. if (idx > -1) {
  47564. var runtimeAnimations = this._runtimeAnimations;
  47565. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47566. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47567. continue;
  47568. }
  47569. runtimeAnimations[index].dispose();
  47570. runtimeAnimations.splice(index, 1);
  47571. }
  47572. if (runtimeAnimations.length == 0) {
  47573. this._scene._activeAnimatables.splice(idx, 1);
  47574. if (this.onAnimationEnd) {
  47575. this.onAnimationEnd();
  47576. }
  47577. }
  47578. }
  47579. }
  47580. else {
  47581. var index = this._scene._activeAnimatables.indexOf(this);
  47582. if (index > -1) {
  47583. this._scene._activeAnimatables.splice(index, 1);
  47584. var runtimeAnimations = this._runtimeAnimations;
  47585. for (var index = 0; index < runtimeAnimations.length; index++) {
  47586. runtimeAnimations[index].dispose();
  47587. }
  47588. if (this.onAnimationEnd) {
  47589. this.onAnimationEnd();
  47590. }
  47591. }
  47592. }
  47593. };
  47594. Animatable.prototype._animate = function (delay) {
  47595. if (this._paused) {
  47596. this.animationStarted = false;
  47597. if (this._pausedDelay === null) {
  47598. this._pausedDelay = delay;
  47599. }
  47600. return true;
  47601. }
  47602. if (this._localDelayOffset === null) {
  47603. this._localDelayOffset = delay;
  47604. this._pausedDelay = null;
  47605. }
  47606. else if (this._pausedDelay !== null) {
  47607. this._localDelayOffset += delay - this._pausedDelay;
  47608. this._pausedDelay = null;
  47609. }
  47610. // Animating
  47611. var running = false;
  47612. var runtimeAnimations = this._runtimeAnimations;
  47613. var index;
  47614. for (index = 0; index < runtimeAnimations.length; index++) {
  47615. var animation = runtimeAnimations[index];
  47616. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47617. running = running || isRunning;
  47618. }
  47619. this.animationStarted = running;
  47620. if (!running) {
  47621. // Remove from active animatables
  47622. index = this._scene._activeAnimatables.indexOf(this);
  47623. this._scene._activeAnimatables.splice(index, 1);
  47624. // Dispose all runtime animations
  47625. for (index = 0; index < runtimeAnimations.length; index++) {
  47626. runtimeAnimations[index].dispose();
  47627. }
  47628. }
  47629. if (!running && this.onAnimationEnd) {
  47630. this.onAnimationEnd();
  47631. this.onAnimationEnd = null;
  47632. }
  47633. return running;
  47634. };
  47635. return Animatable;
  47636. }());
  47637. BABYLON.Animatable = Animatable;
  47638. })(BABYLON || (BABYLON = {}));
  47639. //# sourceMappingURL=babylon.animatable.js.map
  47640. var BABYLON;
  47641. (function (BABYLON) {
  47642. var EasingFunction = /** @class */ (function () {
  47643. function EasingFunction() {
  47644. // Properties
  47645. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47646. }
  47647. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47648. get: function () {
  47649. return EasingFunction._EASINGMODE_EASEIN;
  47650. },
  47651. enumerable: true,
  47652. configurable: true
  47653. });
  47654. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47655. get: function () {
  47656. return EasingFunction._EASINGMODE_EASEOUT;
  47657. },
  47658. enumerable: true,
  47659. configurable: true
  47660. });
  47661. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47662. get: function () {
  47663. return EasingFunction._EASINGMODE_EASEINOUT;
  47664. },
  47665. enumerable: true,
  47666. configurable: true
  47667. });
  47668. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47669. var n = Math.min(Math.max(easingMode, 0), 2);
  47670. this._easingMode = n;
  47671. };
  47672. EasingFunction.prototype.getEasingMode = function () {
  47673. return this._easingMode;
  47674. };
  47675. EasingFunction.prototype.easeInCore = function (gradient) {
  47676. throw new Error('You must implement this method');
  47677. };
  47678. EasingFunction.prototype.ease = function (gradient) {
  47679. switch (this._easingMode) {
  47680. case EasingFunction.EASINGMODE_EASEIN:
  47681. return this.easeInCore(gradient);
  47682. case EasingFunction.EASINGMODE_EASEOUT:
  47683. return (1 - this.easeInCore(1 - gradient));
  47684. }
  47685. if (gradient >= 0.5) {
  47686. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47687. }
  47688. return (this.easeInCore(gradient * 2) * 0.5);
  47689. };
  47690. //Statics
  47691. EasingFunction._EASINGMODE_EASEIN = 0;
  47692. EasingFunction._EASINGMODE_EASEOUT = 1;
  47693. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47694. return EasingFunction;
  47695. }());
  47696. BABYLON.EasingFunction = EasingFunction;
  47697. var CircleEase = /** @class */ (function (_super) {
  47698. __extends(CircleEase, _super);
  47699. function CircleEase() {
  47700. return _super !== null && _super.apply(this, arguments) || this;
  47701. }
  47702. CircleEase.prototype.easeInCore = function (gradient) {
  47703. gradient = Math.max(0, Math.min(1, gradient));
  47704. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47705. };
  47706. return CircleEase;
  47707. }(EasingFunction));
  47708. BABYLON.CircleEase = CircleEase;
  47709. var BackEase = /** @class */ (function (_super) {
  47710. __extends(BackEase, _super);
  47711. function BackEase(amplitude) {
  47712. if (amplitude === void 0) { amplitude = 1; }
  47713. var _this = _super.call(this) || this;
  47714. _this.amplitude = amplitude;
  47715. return _this;
  47716. }
  47717. BackEase.prototype.easeInCore = function (gradient) {
  47718. var num = Math.max(0, this.amplitude);
  47719. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47720. };
  47721. return BackEase;
  47722. }(EasingFunction));
  47723. BABYLON.BackEase = BackEase;
  47724. var BounceEase = /** @class */ (function (_super) {
  47725. __extends(BounceEase, _super);
  47726. function BounceEase(bounces, bounciness) {
  47727. if (bounces === void 0) { bounces = 3; }
  47728. if (bounciness === void 0) { bounciness = 2; }
  47729. var _this = _super.call(this) || this;
  47730. _this.bounces = bounces;
  47731. _this.bounciness = bounciness;
  47732. return _this;
  47733. }
  47734. BounceEase.prototype.easeInCore = function (gradient) {
  47735. var y = Math.max(0.0, this.bounces);
  47736. var bounciness = this.bounciness;
  47737. if (bounciness <= 1.0) {
  47738. bounciness = 1.001;
  47739. }
  47740. var num9 = Math.pow(bounciness, y);
  47741. var num5 = 1.0 - bounciness;
  47742. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47743. var num15 = gradient * num4;
  47744. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47745. var num3 = Math.floor(num65);
  47746. var num13 = num3 + 1.0;
  47747. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47748. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47749. var num7 = (num8 + num12) * 0.5;
  47750. var num6 = gradient - num7;
  47751. var num2 = num7 - num8;
  47752. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47753. };
  47754. return BounceEase;
  47755. }(EasingFunction));
  47756. BABYLON.BounceEase = BounceEase;
  47757. var CubicEase = /** @class */ (function (_super) {
  47758. __extends(CubicEase, _super);
  47759. function CubicEase() {
  47760. return _super !== null && _super.apply(this, arguments) || this;
  47761. }
  47762. CubicEase.prototype.easeInCore = function (gradient) {
  47763. return (gradient * gradient * gradient);
  47764. };
  47765. return CubicEase;
  47766. }(EasingFunction));
  47767. BABYLON.CubicEase = CubicEase;
  47768. var ElasticEase = /** @class */ (function (_super) {
  47769. __extends(ElasticEase, _super);
  47770. function ElasticEase(oscillations, springiness) {
  47771. if (oscillations === void 0) { oscillations = 3; }
  47772. if (springiness === void 0) { springiness = 3; }
  47773. var _this = _super.call(this) || this;
  47774. _this.oscillations = oscillations;
  47775. _this.springiness = springiness;
  47776. return _this;
  47777. }
  47778. ElasticEase.prototype.easeInCore = function (gradient) {
  47779. var num2;
  47780. var num3 = Math.max(0.0, this.oscillations);
  47781. var num = Math.max(0.0, this.springiness);
  47782. if (num == 0) {
  47783. num2 = gradient;
  47784. }
  47785. else {
  47786. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47787. }
  47788. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47789. };
  47790. return ElasticEase;
  47791. }(EasingFunction));
  47792. BABYLON.ElasticEase = ElasticEase;
  47793. var ExponentialEase = /** @class */ (function (_super) {
  47794. __extends(ExponentialEase, _super);
  47795. function ExponentialEase(exponent) {
  47796. if (exponent === void 0) { exponent = 2; }
  47797. var _this = _super.call(this) || this;
  47798. _this.exponent = exponent;
  47799. return _this;
  47800. }
  47801. ExponentialEase.prototype.easeInCore = function (gradient) {
  47802. if (this.exponent <= 0) {
  47803. return gradient;
  47804. }
  47805. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47806. };
  47807. return ExponentialEase;
  47808. }(EasingFunction));
  47809. BABYLON.ExponentialEase = ExponentialEase;
  47810. var PowerEase = /** @class */ (function (_super) {
  47811. __extends(PowerEase, _super);
  47812. function PowerEase(power) {
  47813. if (power === void 0) { power = 2; }
  47814. var _this = _super.call(this) || this;
  47815. _this.power = power;
  47816. return _this;
  47817. }
  47818. PowerEase.prototype.easeInCore = function (gradient) {
  47819. var y = Math.max(0.0, this.power);
  47820. return Math.pow(gradient, y);
  47821. };
  47822. return PowerEase;
  47823. }(EasingFunction));
  47824. BABYLON.PowerEase = PowerEase;
  47825. var QuadraticEase = /** @class */ (function (_super) {
  47826. __extends(QuadraticEase, _super);
  47827. function QuadraticEase() {
  47828. return _super !== null && _super.apply(this, arguments) || this;
  47829. }
  47830. QuadraticEase.prototype.easeInCore = function (gradient) {
  47831. return (gradient * gradient);
  47832. };
  47833. return QuadraticEase;
  47834. }(EasingFunction));
  47835. BABYLON.QuadraticEase = QuadraticEase;
  47836. var QuarticEase = /** @class */ (function (_super) {
  47837. __extends(QuarticEase, _super);
  47838. function QuarticEase() {
  47839. return _super !== null && _super.apply(this, arguments) || this;
  47840. }
  47841. QuarticEase.prototype.easeInCore = function (gradient) {
  47842. return (gradient * gradient * gradient * gradient);
  47843. };
  47844. return QuarticEase;
  47845. }(EasingFunction));
  47846. BABYLON.QuarticEase = QuarticEase;
  47847. var QuinticEase = /** @class */ (function (_super) {
  47848. __extends(QuinticEase, _super);
  47849. function QuinticEase() {
  47850. return _super !== null && _super.apply(this, arguments) || this;
  47851. }
  47852. QuinticEase.prototype.easeInCore = function (gradient) {
  47853. return (gradient * gradient * gradient * gradient * gradient);
  47854. };
  47855. return QuinticEase;
  47856. }(EasingFunction));
  47857. BABYLON.QuinticEase = QuinticEase;
  47858. var SineEase = /** @class */ (function (_super) {
  47859. __extends(SineEase, _super);
  47860. function SineEase() {
  47861. return _super !== null && _super.apply(this, arguments) || this;
  47862. }
  47863. SineEase.prototype.easeInCore = function (gradient) {
  47864. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47865. };
  47866. return SineEase;
  47867. }(EasingFunction));
  47868. BABYLON.SineEase = SineEase;
  47869. var BezierCurveEase = /** @class */ (function (_super) {
  47870. __extends(BezierCurveEase, _super);
  47871. function BezierCurveEase(x1, y1, x2, y2) {
  47872. if (x1 === void 0) { x1 = 0; }
  47873. if (y1 === void 0) { y1 = 0; }
  47874. if (x2 === void 0) { x2 = 1; }
  47875. if (y2 === void 0) { y2 = 1; }
  47876. var _this = _super.call(this) || this;
  47877. _this.x1 = x1;
  47878. _this.y1 = y1;
  47879. _this.x2 = x2;
  47880. _this.y2 = y2;
  47881. return _this;
  47882. }
  47883. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47884. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47885. };
  47886. return BezierCurveEase;
  47887. }(EasingFunction));
  47888. BABYLON.BezierCurveEase = BezierCurveEase;
  47889. })(BABYLON || (BABYLON = {}));
  47890. //# sourceMappingURL=babylon.easing.js.map
  47891. var BABYLON;
  47892. (function (BABYLON) {
  47893. var Condition = /** @class */ (function () {
  47894. function Condition(actionManager) {
  47895. this._actionManager = actionManager;
  47896. }
  47897. Condition.prototype.isValid = function () {
  47898. return true;
  47899. };
  47900. Condition.prototype._getProperty = function (propertyPath) {
  47901. return this._actionManager._getProperty(propertyPath);
  47902. };
  47903. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47904. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47905. };
  47906. Condition.prototype.serialize = function () {
  47907. };
  47908. Condition.prototype._serialize = function (serializedCondition) {
  47909. return {
  47910. type: 2,
  47911. children: [],
  47912. name: serializedCondition.name,
  47913. properties: serializedCondition.properties
  47914. };
  47915. };
  47916. return Condition;
  47917. }());
  47918. BABYLON.Condition = Condition;
  47919. var ValueCondition = /** @class */ (function (_super) {
  47920. __extends(ValueCondition, _super);
  47921. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47922. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47923. var _this = _super.call(this, actionManager) || this;
  47924. _this.propertyPath = propertyPath;
  47925. _this.value = value;
  47926. _this.operator = operator;
  47927. _this._target = target;
  47928. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47929. _this._property = _this._getProperty(_this.propertyPath);
  47930. return _this;
  47931. }
  47932. Object.defineProperty(ValueCondition, "IsEqual", {
  47933. get: function () {
  47934. return ValueCondition._IsEqual;
  47935. },
  47936. enumerable: true,
  47937. configurable: true
  47938. });
  47939. Object.defineProperty(ValueCondition, "IsDifferent", {
  47940. get: function () {
  47941. return ValueCondition._IsDifferent;
  47942. },
  47943. enumerable: true,
  47944. configurable: true
  47945. });
  47946. Object.defineProperty(ValueCondition, "IsGreater", {
  47947. get: function () {
  47948. return ValueCondition._IsGreater;
  47949. },
  47950. enumerable: true,
  47951. configurable: true
  47952. });
  47953. Object.defineProperty(ValueCondition, "IsLesser", {
  47954. get: function () {
  47955. return ValueCondition._IsLesser;
  47956. },
  47957. enumerable: true,
  47958. configurable: true
  47959. });
  47960. // Methods
  47961. ValueCondition.prototype.isValid = function () {
  47962. switch (this.operator) {
  47963. case ValueCondition.IsGreater:
  47964. return this._effectiveTarget[this._property] > this.value;
  47965. case ValueCondition.IsLesser:
  47966. return this._effectiveTarget[this._property] < this.value;
  47967. case ValueCondition.IsEqual:
  47968. case ValueCondition.IsDifferent:
  47969. var check;
  47970. if (this.value.equals) {
  47971. check = this.value.equals(this._effectiveTarget[this._property]);
  47972. }
  47973. else {
  47974. check = this.value === this._effectiveTarget[this._property];
  47975. }
  47976. return this.operator === ValueCondition.IsEqual ? check : !check;
  47977. }
  47978. return false;
  47979. };
  47980. ValueCondition.prototype.serialize = function () {
  47981. return this._serialize({
  47982. name: "ValueCondition",
  47983. properties: [
  47984. BABYLON.Action._GetTargetProperty(this._target),
  47985. { name: "propertyPath", value: this.propertyPath },
  47986. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47987. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47988. ]
  47989. });
  47990. };
  47991. ValueCondition.GetOperatorName = function (operator) {
  47992. switch (operator) {
  47993. case ValueCondition._IsEqual: return "IsEqual";
  47994. case ValueCondition._IsDifferent: return "IsDifferent";
  47995. case ValueCondition._IsGreater: return "IsGreater";
  47996. case ValueCondition._IsLesser: return "IsLesser";
  47997. default: return "";
  47998. }
  47999. };
  48000. // Statics
  48001. ValueCondition._IsEqual = 0;
  48002. ValueCondition._IsDifferent = 1;
  48003. ValueCondition._IsGreater = 2;
  48004. ValueCondition._IsLesser = 3;
  48005. return ValueCondition;
  48006. }(Condition));
  48007. BABYLON.ValueCondition = ValueCondition;
  48008. var PredicateCondition = /** @class */ (function (_super) {
  48009. __extends(PredicateCondition, _super);
  48010. function PredicateCondition(actionManager, predicate) {
  48011. var _this = _super.call(this, actionManager) || this;
  48012. _this.predicate = predicate;
  48013. return _this;
  48014. }
  48015. PredicateCondition.prototype.isValid = function () {
  48016. return this.predicate();
  48017. };
  48018. return PredicateCondition;
  48019. }(Condition));
  48020. BABYLON.PredicateCondition = PredicateCondition;
  48021. var StateCondition = /** @class */ (function (_super) {
  48022. __extends(StateCondition, _super);
  48023. function StateCondition(actionManager, target, value) {
  48024. var _this = _super.call(this, actionManager) || this;
  48025. _this.value = value;
  48026. _this._target = target;
  48027. return _this;
  48028. }
  48029. // Methods
  48030. StateCondition.prototype.isValid = function () {
  48031. return this._target.state === this.value;
  48032. };
  48033. StateCondition.prototype.serialize = function () {
  48034. return this._serialize({
  48035. name: "StateCondition",
  48036. properties: [
  48037. BABYLON.Action._GetTargetProperty(this._target),
  48038. { name: "value", value: this.value }
  48039. ]
  48040. });
  48041. };
  48042. return StateCondition;
  48043. }(Condition));
  48044. BABYLON.StateCondition = StateCondition;
  48045. })(BABYLON || (BABYLON = {}));
  48046. //# sourceMappingURL=babylon.condition.js.map
  48047. var BABYLON;
  48048. (function (BABYLON) {
  48049. var Action = /** @class */ (function () {
  48050. function Action(triggerOptions, condition) {
  48051. this.triggerOptions = triggerOptions;
  48052. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48053. if (triggerOptions.parameter) {
  48054. this.trigger = triggerOptions.trigger;
  48055. this._triggerParameter = triggerOptions.parameter;
  48056. }
  48057. else {
  48058. this.trigger = triggerOptions;
  48059. }
  48060. this._nextActiveAction = this;
  48061. this._condition = condition;
  48062. }
  48063. // Methods
  48064. Action.prototype._prepare = function () {
  48065. };
  48066. Action.prototype.getTriggerParameter = function () {
  48067. return this._triggerParameter;
  48068. };
  48069. Action.prototype._executeCurrent = function (evt) {
  48070. if (this._nextActiveAction._condition) {
  48071. var condition = this._nextActiveAction._condition;
  48072. var currentRenderId = this._actionManager.getScene().getRenderId();
  48073. // We cache the current evaluation for the current frame
  48074. if (condition._evaluationId === currentRenderId) {
  48075. if (!condition._currentResult) {
  48076. return;
  48077. }
  48078. }
  48079. else {
  48080. condition._evaluationId = currentRenderId;
  48081. if (!condition.isValid()) {
  48082. condition._currentResult = false;
  48083. return;
  48084. }
  48085. condition._currentResult = true;
  48086. }
  48087. }
  48088. this.onBeforeExecuteObservable.notifyObservers(this);
  48089. this._nextActiveAction.execute(evt);
  48090. this.skipToNextActiveAction();
  48091. };
  48092. Action.prototype.execute = function (evt) {
  48093. };
  48094. Action.prototype.skipToNextActiveAction = function () {
  48095. if (this._nextActiveAction._child) {
  48096. if (!this._nextActiveAction._child._actionManager) {
  48097. this._nextActiveAction._child._actionManager = this._actionManager;
  48098. }
  48099. this._nextActiveAction = this._nextActiveAction._child;
  48100. }
  48101. else {
  48102. this._nextActiveAction = this;
  48103. }
  48104. };
  48105. Action.prototype.then = function (action) {
  48106. this._child = action;
  48107. action._actionManager = this._actionManager;
  48108. action._prepare();
  48109. return action;
  48110. };
  48111. Action.prototype._getProperty = function (propertyPath) {
  48112. return this._actionManager._getProperty(propertyPath);
  48113. };
  48114. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48115. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48116. };
  48117. Action.prototype.serialize = function (parent) {
  48118. };
  48119. // Called by BABYLON.Action objects in serialize(...). Internal use
  48120. Action.prototype._serialize = function (serializedAction, parent) {
  48121. var serializationObject = {
  48122. type: 1,
  48123. children: [],
  48124. name: serializedAction.name,
  48125. properties: serializedAction.properties || []
  48126. };
  48127. // Serialize child
  48128. if (this._child) {
  48129. this._child.serialize(serializationObject);
  48130. }
  48131. // Check if "this" has a condition
  48132. if (this._condition) {
  48133. var serializedCondition = this._condition.serialize();
  48134. serializedCondition.children.push(serializationObject);
  48135. if (parent) {
  48136. parent.children.push(serializedCondition);
  48137. }
  48138. return serializedCondition;
  48139. }
  48140. if (parent) {
  48141. parent.children.push(serializationObject);
  48142. }
  48143. return serializationObject;
  48144. };
  48145. Action._SerializeValueAsString = function (value) {
  48146. if (typeof value === "number") {
  48147. return value.toString();
  48148. }
  48149. if (typeof value === "boolean") {
  48150. return value ? "true" : "false";
  48151. }
  48152. if (value instanceof BABYLON.Vector2) {
  48153. return value.x + ", " + value.y;
  48154. }
  48155. if (value instanceof BABYLON.Vector3) {
  48156. return value.x + ", " + value.y + ", " + value.z;
  48157. }
  48158. if (value instanceof BABYLON.Color3) {
  48159. return value.r + ", " + value.g + ", " + value.b;
  48160. }
  48161. if (value instanceof BABYLON.Color4) {
  48162. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48163. }
  48164. return value; // string
  48165. };
  48166. Action._GetTargetProperty = function (target) {
  48167. return {
  48168. name: "target",
  48169. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48170. : target instanceof BABYLON.Light ? "LightProperties"
  48171. : target instanceof BABYLON.Camera ? "CameraProperties"
  48172. : "SceneProperties",
  48173. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48174. };
  48175. };
  48176. return Action;
  48177. }());
  48178. BABYLON.Action = Action;
  48179. })(BABYLON || (BABYLON = {}));
  48180. //# sourceMappingURL=babylon.action.js.map
  48181. var BABYLON;
  48182. (function (BABYLON) {
  48183. /**
  48184. * ActionEvent is the event beint sent when an action is triggered.
  48185. */
  48186. var ActionEvent = /** @class */ (function () {
  48187. /**
  48188. * @param source The mesh or sprite that triggered the action.
  48189. * @param pointerX The X mouse cursor position at the time of the event
  48190. * @param pointerY The Y mouse cursor position at the time of the event
  48191. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48192. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48193. */
  48194. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48195. this.source = source;
  48196. this.pointerX = pointerX;
  48197. this.pointerY = pointerY;
  48198. this.meshUnderPointer = meshUnderPointer;
  48199. this.sourceEvent = sourceEvent;
  48200. this.additionalData = additionalData;
  48201. }
  48202. /**
  48203. * Helper function to auto-create an ActionEvent from a source mesh.
  48204. * @param source The source mesh that triggered the event
  48205. * @param evt {Event} The original (browser) event
  48206. */
  48207. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48208. var scene = source.getScene();
  48209. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48210. };
  48211. /**
  48212. * Helper function to auto-create an ActionEvent from a source mesh.
  48213. * @param source The source sprite that triggered the event
  48214. * @param scene Scene associated with the sprite
  48215. * @param evt {Event} The original (browser) event
  48216. */
  48217. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48218. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48219. };
  48220. /**
  48221. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48222. * @param scene the scene where the event occurred
  48223. * @param evt {Event} The original (browser) event
  48224. */
  48225. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48226. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48227. };
  48228. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48229. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48230. };
  48231. return ActionEvent;
  48232. }());
  48233. BABYLON.ActionEvent = ActionEvent;
  48234. /**
  48235. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48236. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48237. */
  48238. var ActionManager = /** @class */ (function () {
  48239. function ActionManager(scene) {
  48240. // Members
  48241. this.actions = new Array();
  48242. this.hoverCursor = '';
  48243. this._scene = scene;
  48244. scene._actionManagers.push(this);
  48245. }
  48246. Object.defineProperty(ActionManager, "NothingTrigger", {
  48247. get: function () {
  48248. return ActionManager._NothingTrigger;
  48249. },
  48250. enumerable: true,
  48251. configurable: true
  48252. });
  48253. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48254. get: function () {
  48255. return ActionManager._OnPickTrigger;
  48256. },
  48257. enumerable: true,
  48258. configurable: true
  48259. });
  48260. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48261. get: function () {
  48262. return ActionManager._OnLeftPickTrigger;
  48263. },
  48264. enumerable: true,
  48265. configurable: true
  48266. });
  48267. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48268. get: function () {
  48269. return ActionManager._OnRightPickTrigger;
  48270. },
  48271. enumerable: true,
  48272. configurable: true
  48273. });
  48274. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48275. get: function () {
  48276. return ActionManager._OnCenterPickTrigger;
  48277. },
  48278. enumerable: true,
  48279. configurable: true
  48280. });
  48281. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48282. get: function () {
  48283. return ActionManager._OnPickDownTrigger;
  48284. },
  48285. enumerable: true,
  48286. configurable: true
  48287. });
  48288. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48289. get: function () {
  48290. return ActionManager._OnDoublePickTrigger;
  48291. },
  48292. enumerable: true,
  48293. configurable: true
  48294. });
  48295. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48296. get: function () {
  48297. return ActionManager._OnPickUpTrigger;
  48298. },
  48299. enumerable: true,
  48300. configurable: true
  48301. });
  48302. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48303. /// This trigger will only be raised if you also declared a OnPickDown
  48304. get: function () {
  48305. return ActionManager._OnPickOutTrigger;
  48306. },
  48307. enumerable: true,
  48308. configurable: true
  48309. });
  48310. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48311. get: function () {
  48312. return ActionManager._OnLongPressTrigger;
  48313. },
  48314. enumerable: true,
  48315. configurable: true
  48316. });
  48317. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48318. get: function () {
  48319. return ActionManager._OnPointerOverTrigger;
  48320. },
  48321. enumerable: true,
  48322. configurable: true
  48323. });
  48324. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48325. get: function () {
  48326. return ActionManager._OnPointerOutTrigger;
  48327. },
  48328. enumerable: true,
  48329. configurable: true
  48330. });
  48331. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48332. get: function () {
  48333. return ActionManager._OnEveryFrameTrigger;
  48334. },
  48335. enumerable: true,
  48336. configurable: true
  48337. });
  48338. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48339. get: function () {
  48340. return ActionManager._OnIntersectionEnterTrigger;
  48341. },
  48342. enumerable: true,
  48343. configurable: true
  48344. });
  48345. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48346. get: function () {
  48347. return ActionManager._OnIntersectionExitTrigger;
  48348. },
  48349. enumerable: true,
  48350. configurable: true
  48351. });
  48352. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48353. get: function () {
  48354. return ActionManager._OnKeyDownTrigger;
  48355. },
  48356. enumerable: true,
  48357. configurable: true
  48358. });
  48359. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48360. get: function () {
  48361. return ActionManager._OnKeyUpTrigger;
  48362. },
  48363. enumerable: true,
  48364. configurable: true
  48365. });
  48366. // Methods
  48367. ActionManager.prototype.dispose = function () {
  48368. var index = this._scene._actionManagers.indexOf(this);
  48369. for (var i = 0; i < this.actions.length; i++) {
  48370. var action = this.actions[i];
  48371. ActionManager.Triggers[action.trigger]--;
  48372. if (ActionManager.Triggers[action.trigger] === 0) {
  48373. delete ActionManager.Triggers[action.trigger];
  48374. }
  48375. }
  48376. if (index > -1) {
  48377. this._scene._actionManagers.splice(index, 1);
  48378. }
  48379. };
  48380. ActionManager.prototype.getScene = function () {
  48381. return this._scene;
  48382. };
  48383. /**
  48384. * Does this action manager handles actions of any of the given triggers
  48385. * @param {number[]} triggers - the triggers to be tested
  48386. * @return {boolean} whether one (or more) of the triggers is handeled
  48387. */
  48388. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48389. for (var index = 0; index < this.actions.length; index++) {
  48390. var action = this.actions[index];
  48391. if (triggers.indexOf(action.trigger) > -1) {
  48392. return true;
  48393. }
  48394. }
  48395. return false;
  48396. };
  48397. /**
  48398. * Does this action manager handles actions of a given trigger
  48399. * @param {number} trigger - the trigger to be tested
  48400. * @return {boolean} whether the trigger is handeled
  48401. */
  48402. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48403. for (var index = 0; index < this.actions.length; index++) {
  48404. var action = this.actions[index];
  48405. if (action.trigger === trigger) {
  48406. return true;
  48407. }
  48408. }
  48409. return false;
  48410. };
  48411. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48412. /**
  48413. * Does this action manager has pointer triggers
  48414. * @return {boolean} whether or not it has pointer triggers
  48415. */
  48416. get: function () {
  48417. for (var index = 0; index < this.actions.length; index++) {
  48418. var action = this.actions[index];
  48419. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48420. return true;
  48421. }
  48422. }
  48423. return false;
  48424. },
  48425. enumerable: true,
  48426. configurable: true
  48427. });
  48428. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48429. /**
  48430. * Does this action manager has pick triggers
  48431. * @return {boolean} whether or not it has pick triggers
  48432. */
  48433. get: function () {
  48434. for (var index = 0; index < this.actions.length; index++) {
  48435. var action = this.actions[index];
  48436. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48437. return true;
  48438. }
  48439. }
  48440. return false;
  48441. },
  48442. enumerable: true,
  48443. configurable: true
  48444. });
  48445. Object.defineProperty(ActionManager, "HasTriggers", {
  48446. /**
  48447. * Does exist one action manager with at least one trigger
  48448. * @return {boolean} whether or not it exists one action manager with one trigger
  48449. **/
  48450. get: function () {
  48451. for (var t in ActionManager.Triggers) {
  48452. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48453. return true;
  48454. }
  48455. }
  48456. return false;
  48457. },
  48458. enumerable: true,
  48459. configurable: true
  48460. });
  48461. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48462. /**
  48463. * Does exist one action manager with at least one pick trigger
  48464. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48465. **/
  48466. get: function () {
  48467. for (var t in ActionManager.Triggers) {
  48468. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48469. var t_int = parseInt(t);
  48470. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48471. return true;
  48472. }
  48473. }
  48474. }
  48475. return false;
  48476. },
  48477. enumerable: true,
  48478. configurable: true
  48479. });
  48480. /**
  48481. * Does exist one action manager that handles actions of a given trigger
  48482. * @param {number} trigger - the trigger to be tested
  48483. * @return {boolean} whether the trigger is handeled by at least one action manager
  48484. **/
  48485. ActionManager.HasSpecificTrigger = function (trigger) {
  48486. for (var t in ActionManager.Triggers) {
  48487. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48488. var t_int = parseInt(t);
  48489. if (t_int === trigger) {
  48490. return true;
  48491. }
  48492. }
  48493. }
  48494. return false;
  48495. };
  48496. /**
  48497. * Registers an action to this action manager
  48498. * @param {BABYLON.Action} action - the action to be registered
  48499. * @return {BABYLON.Action} the action amended (prepared) after registration
  48500. */
  48501. ActionManager.prototype.registerAction = function (action) {
  48502. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48503. if (this.getScene().actionManager !== this) {
  48504. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48505. return null;
  48506. }
  48507. }
  48508. this.actions.push(action);
  48509. if (ActionManager.Triggers[action.trigger]) {
  48510. ActionManager.Triggers[action.trigger]++;
  48511. }
  48512. else {
  48513. ActionManager.Triggers[action.trigger] = 1;
  48514. }
  48515. action._actionManager = this;
  48516. action._prepare();
  48517. return action;
  48518. };
  48519. /**
  48520. * Unregisters an action to this action manager
  48521. * @param action The action to be unregistered
  48522. * @return whether the action has been unregistered
  48523. */
  48524. ActionManager.prototype.unregisterAction = function (action) {
  48525. var index = this.actions.indexOf(action);
  48526. if (index !== -1) {
  48527. this.actions.splice(index, 1);
  48528. ActionManager.Triggers[action.trigger] -= 1;
  48529. if (ActionManager.Triggers[action.trigger] === 0) {
  48530. delete ActionManager.Triggers[action.trigger];
  48531. }
  48532. delete action._actionManager;
  48533. return true;
  48534. }
  48535. return false;
  48536. };
  48537. /**
  48538. * Process a specific trigger
  48539. * @param {number} trigger - the trigger to process
  48540. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48541. */
  48542. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48543. for (var index = 0; index < this.actions.length; index++) {
  48544. var action = this.actions[index];
  48545. if (action.trigger === trigger) {
  48546. if (evt) {
  48547. if (trigger === ActionManager.OnKeyUpTrigger
  48548. || trigger === ActionManager.OnKeyDownTrigger) {
  48549. var parameter = action.getTriggerParameter();
  48550. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48551. if (!parameter.toLowerCase) {
  48552. continue;
  48553. }
  48554. var lowerCase = parameter.toLowerCase();
  48555. if (lowerCase !== evt.sourceEvent.key) {
  48556. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48557. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48558. if (actualkey !== lowerCase) {
  48559. continue;
  48560. }
  48561. }
  48562. }
  48563. }
  48564. }
  48565. action._executeCurrent(evt);
  48566. }
  48567. }
  48568. };
  48569. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48570. var properties = propertyPath.split(".");
  48571. for (var index = 0; index < properties.length - 1; index++) {
  48572. target = target[properties[index]];
  48573. }
  48574. return target;
  48575. };
  48576. ActionManager.prototype._getProperty = function (propertyPath) {
  48577. var properties = propertyPath.split(".");
  48578. return properties[properties.length - 1];
  48579. };
  48580. ActionManager.prototype.serialize = function (name) {
  48581. var root = {
  48582. children: new Array(),
  48583. name: name,
  48584. type: 3,
  48585. properties: new Array() // Empty for root but required
  48586. };
  48587. for (var i = 0; i < this.actions.length; i++) {
  48588. var triggerObject = {
  48589. type: 0,
  48590. children: new Array(),
  48591. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48592. properties: new Array()
  48593. };
  48594. var triggerOptions = this.actions[i].triggerOptions;
  48595. if (triggerOptions && typeof triggerOptions !== "number") {
  48596. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48597. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48598. }
  48599. else {
  48600. var parameter = {};
  48601. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48602. if (triggerOptions.parameter.mesh) {
  48603. parameter._meshId = triggerOptions.parameter.mesh.id;
  48604. }
  48605. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48606. }
  48607. }
  48608. // Serialize child action, recursively
  48609. this.actions[i].serialize(triggerObject);
  48610. // Add serialized trigger
  48611. root.children.push(triggerObject);
  48612. }
  48613. return root;
  48614. };
  48615. ActionManager.Parse = function (parsedActions, object, scene) {
  48616. var actionManager = new ActionManager(scene);
  48617. if (object === null)
  48618. scene.actionManager = actionManager;
  48619. else
  48620. object.actionManager = actionManager;
  48621. // instanciate a new object
  48622. var instanciate = function (name, params) {
  48623. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48624. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48625. newInstance.constructor.apply(newInstance, params);
  48626. return newInstance;
  48627. };
  48628. var parseParameter = function (name, value, target, propertyPath) {
  48629. if (propertyPath === null) {
  48630. // String, boolean or float
  48631. var floatValue = parseFloat(value);
  48632. if (value === "true" || value === "false")
  48633. return value === "true";
  48634. else
  48635. return isNaN(floatValue) ? value : floatValue;
  48636. }
  48637. var effectiveTarget = propertyPath.split(".");
  48638. var values = value.split(",");
  48639. // Get effective Target
  48640. for (var i = 0; i < effectiveTarget.length; i++) {
  48641. target = target[effectiveTarget[i]];
  48642. }
  48643. // Return appropriate value with its type
  48644. if (typeof (target) === "boolean")
  48645. return values[0] === "true";
  48646. if (typeof (target) === "string")
  48647. return values[0];
  48648. // Parameters with multiple values such as Vector3 etc.
  48649. var split = new Array();
  48650. for (var i = 0; i < values.length; i++)
  48651. split.push(parseFloat(values[i]));
  48652. if (target instanceof BABYLON.Vector3)
  48653. return BABYLON.Vector3.FromArray(split);
  48654. if (target instanceof BABYLON.Vector4)
  48655. return BABYLON.Vector4.FromArray(split);
  48656. if (target instanceof BABYLON.Color3)
  48657. return BABYLON.Color3.FromArray(split);
  48658. if (target instanceof BABYLON.Color4)
  48659. return BABYLON.Color4.FromArray(split);
  48660. return parseFloat(values[0]);
  48661. };
  48662. // traverse graph per trigger
  48663. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48664. if (combineArray === void 0) { combineArray = null; }
  48665. if (parsedAction.detached)
  48666. return;
  48667. var parameters = new Array();
  48668. var target = null;
  48669. var propertyPath = null;
  48670. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48671. // Parameters
  48672. if (parsedAction.type === 2)
  48673. parameters.push(actionManager);
  48674. else
  48675. parameters.push(trigger);
  48676. if (combine) {
  48677. var actions = new Array();
  48678. for (var j = 0; j < parsedAction.combine.length; j++) {
  48679. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48680. }
  48681. parameters.push(actions);
  48682. }
  48683. else {
  48684. for (var i = 0; i < parsedAction.properties.length; i++) {
  48685. var value = parsedAction.properties[i].value;
  48686. var name = parsedAction.properties[i].name;
  48687. var targetType = parsedAction.properties[i].targetType;
  48688. if (name === "target")
  48689. if (targetType !== null && targetType === "SceneProperties")
  48690. value = target = scene;
  48691. else
  48692. value = target = scene.getNodeByName(value);
  48693. else if (name === "parent")
  48694. value = scene.getNodeByName(value);
  48695. else if (name === "sound")
  48696. value = scene.getSoundByName(value);
  48697. else if (name !== "propertyPath") {
  48698. if (parsedAction.type === 2 && name === "operator")
  48699. value = BABYLON.ValueCondition[value];
  48700. else
  48701. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48702. }
  48703. else {
  48704. propertyPath = value;
  48705. }
  48706. parameters.push(value);
  48707. }
  48708. }
  48709. if (combineArray === null) {
  48710. parameters.push(condition);
  48711. }
  48712. else {
  48713. parameters.push(null);
  48714. }
  48715. // If interpolate value action
  48716. if (parsedAction.name === "InterpolateValueAction") {
  48717. var param = parameters[parameters.length - 2];
  48718. parameters[parameters.length - 1] = param;
  48719. parameters[parameters.length - 2] = condition;
  48720. }
  48721. // Action or condition(s) and not CombineAction
  48722. var newAction = instanciate(parsedAction.name, parameters);
  48723. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48724. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48725. if (action)
  48726. action.then(nothing);
  48727. else
  48728. actionManager.registerAction(nothing);
  48729. action = nothing;
  48730. }
  48731. if (combineArray === null) {
  48732. if (newAction instanceof BABYLON.Condition) {
  48733. condition = newAction;
  48734. newAction = action;
  48735. }
  48736. else {
  48737. condition = null;
  48738. if (action)
  48739. action.then(newAction);
  48740. else
  48741. actionManager.registerAction(newAction);
  48742. }
  48743. }
  48744. else {
  48745. combineArray.push(newAction);
  48746. }
  48747. for (var i = 0; i < parsedAction.children.length; i++)
  48748. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48749. };
  48750. // triggers
  48751. for (var i = 0; i < parsedActions.children.length; i++) {
  48752. var triggerParams;
  48753. var trigger = parsedActions.children[i];
  48754. if (trigger.properties.length > 0) {
  48755. var param = trigger.properties[0].value;
  48756. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48757. if (value._meshId) {
  48758. value.mesh = scene.getMeshByID(value._meshId);
  48759. }
  48760. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48761. }
  48762. else
  48763. triggerParams = ActionManager[trigger.name];
  48764. for (var j = 0; j < trigger.children.length; j++) {
  48765. if (!trigger.detached)
  48766. traverse(trigger.children[j], triggerParams, null, null);
  48767. }
  48768. }
  48769. };
  48770. ActionManager.GetTriggerName = function (trigger) {
  48771. switch (trigger) {
  48772. case 0: return "NothingTrigger";
  48773. case 1: return "OnPickTrigger";
  48774. case 2: return "OnLeftPickTrigger";
  48775. case 3: return "OnRightPickTrigger";
  48776. case 4: return "OnCenterPickTrigger";
  48777. case 5: return "OnPickDownTrigger";
  48778. case 6: return "OnPickUpTrigger";
  48779. case 7: return "OnLongPressTrigger";
  48780. case 8: return "OnPointerOverTrigger";
  48781. case 9: return "OnPointerOutTrigger";
  48782. case 10: return "OnEveryFrameTrigger";
  48783. case 11: return "OnIntersectionEnterTrigger";
  48784. case 12: return "OnIntersectionExitTrigger";
  48785. case 13: return "OnKeyDownTrigger";
  48786. case 14: return "OnKeyUpTrigger";
  48787. case 15: return "OnPickOutTrigger";
  48788. default: return "";
  48789. }
  48790. };
  48791. // Statics
  48792. ActionManager._NothingTrigger = 0;
  48793. ActionManager._OnPickTrigger = 1;
  48794. ActionManager._OnLeftPickTrigger = 2;
  48795. ActionManager._OnRightPickTrigger = 3;
  48796. ActionManager._OnCenterPickTrigger = 4;
  48797. ActionManager._OnPickDownTrigger = 5;
  48798. ActionManager._OnDoublePickTrigger = 6;
  48799. ActionManager._OnPickUpTrigger = 7;
  48800. ActionManager._OnLongPressTrigger = 8;
  48801. ActionManager._OnPointerOverTrigger = 9;
  48802. ActionManager._OnPointerOutTrigger = 10;
  48803. ActionManager._OnEveryFrameTrigger = 11;
  48804. ActionManager._OnIntersectionEnterTrigger = 12;
  48805. ActionManager._OnIntersectionExitTrigger = 13;
  48806. ActionManager._OnKeyDownTrigger = 14;
  48807. ActionManager._OnKeyUpTrigger = 15;
  48808. ActionManager._OnPickOutTrigger = 16;
  48809. ActionManager.Triggers = {};
  48810. return ActionManager;
  48811. }());
  48812. BABYLON.ActionManager = ActionManager;
  48813. })(BABYLON || (BABYLON = {}));
  48814. //# sourceMappingURL=babylon.actionManager.js.map
  48815. var BABYLON;
  48816. (function (BABYLON) {
  48817. var InterpolateValueAction = /** @class */ (function (_super) {
  48818. __extends(InterpolateValueAction, _super);
  48819. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48820. if (duration === void 0) { duration = 1000; }
  48821. var _this = _super.call(this, triggerOptions, condition) || this;
  48822. _this.propertyPath = propertyPath;
  48823. _this.value = value;
  48824. _this.duration = duration;
  48825. _this.stopOtherAnimations = stopOtherAnimations;
  48826. _this.onInterpolationDone = onInterpolationDone;
  48827. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48828. _this._target = _this._effectiveTarget = target;
  48829. return _this;
  48830. }
  48831. InterpolateValueAction.prototype._prepare = function () {
  48832. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48833. this._property = this._getProperty(this.propertyPath);
  48834. };
  48835. InterpolateValueAction.prototype.execute = function () {
  48836. var _this = this;
  48837. var scene = this._actionManager.getScene();
  48838. var keys = [
  48839. {
  48840. frame: 0,
  48841. value: this._effectiveTarget[this._property]
  48842. }, {
  48843. frame: 100,
  48844. value: this.value
  48845. }
  48846. ];
  48847. var dataType;
  48848. if (typeof this.value === "number") {
  48849. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48850. }
  48851. else if (this.value instanceof BABYLON.Color3) {
  48852. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48853. }
  48854. else if (this.value instanceof BABYLON.Vector3) {
  48855. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48856. }
  48857. else if (this.value instanceof BABYLON.Matrix) {
  48858. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48859. }
  48860. else if (this.value instanceof BABYLON.Quaternion) {
  48861. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48862. }
  48863. else {
  48864. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48865. return;
  48866. }
  48867. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48868. animation.setKeys(keys);
  48869. if (this.stopOtherAnimations) {
  48870. scene.stopAnimation(this._effectiveTarget);
  48871. }
  48872. var wrapper = function () {
  48873. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48874. if (_this.onInterpolationDone) {
  48875. _this.onInterpolationDone();
  48876. }
  48877. };
  48878. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48879. };
  48880. InterpolateValueAction.prototype.serialize = function (parent) {
  48881. return _super.prototype._serialize.call(this, {
  48882. name: "InterpolateValueAction",
  48883. properties: [
  48884. BABYLON.Action._GetTargetProperty(this._target),
  48885. { name: "propertyPath", value: this.propertyPath },
  48886. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48887. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48888. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48889. ]
  48890. }, parent);
  48891. };
  48892. return InterpolateValueAction;
  48893. }(BABYLON.Action));
  48894. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48895. })(BABYLON || (BABYLON = {}));
  48896. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48897. var BABYLON;
  48898. (function (BABYLON) {
  48899. var SwitchBooleanAction = /** @class */ (function (_super) {
  48900. __extends(SwitchBooleanAction, _super);
  48901. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48902. var _this = _super.call(this, triggerOptions, condition) || this;
  48903. _this.propertyPath = propertyPath;
  48904. _this._target = _this._effectiveTarget = target;
  48905. return _this;
  48906. }
  48907. SwitchBooleanAction.prototype._prepare = function () {
  48908. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48909. this._property = this._getProperty(this.propertyPath);
  48910. };
  48911. SwitchBooleanAction.prototype.execute = function () {
  48912. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48913. };
  48914. SwitchBooleanAction.prototype.serialize = function (parent) {
  48915. return _super.prototype._serialize.call(this, {
  48916. name: "SwitchBooleanAction",
  48917. properties: [
  48918. BABYLON.Action._GetTargetProperty(this._target),
  48919. { name: "propertyPath", value: this.propertyPath }
  48920. ]
  48921. }, parent);
  48922. };
  48923. return SwitchBooleanAction;
  48924. }(BABYLON.Action));
  48925. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48926. var SetStateAction = /** @class */ (function (_super) {
  48927. __extends(SetStateAction, _super);
  48928. function SetStateAction(triggerOptions, target, value, condition) {
  48929. var _this = _super.call(this, triggerOptions, condition) || this;
  48930. _this.value = value;
  48931. _this._target = target;
  48932. return _this;
  48933. }
  48934. SetStateAction.prototype.execute = function () {
  48935. this._target.state = this.value;
  48936. };
  48937. SetStateAction.prototype.serialize = function (parent) {
  48938. return _super.prototype._serialize.call(this, {
  48939. name: "SetStateAction",
  48940. properties: [
  48941. BABYLON.Action._GetTargetProperty(this._target),
  48942. { name: "value", value: this.value }
  48943. ]
  48944. }, parent);
  48945. };
  48946. return SetStateAction;
  48947. }(BABYLON.Action));
  48948. BABYLON.SetStateAction = SetStateAction;
  48949. var SetValueAction = /** @class */ (function (_super) {
  48950. __extends(SetValueAction, _super);
  48951. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48952. var _this = _super.call(this, triggerOptions, condition) || this;
  48953. _this.propertyPath = propertyPath;
  48954. _this.value = value;
  48955. _this._target = _this._effectiveTarget = target;
  48956. return _this;
  48957. }
  48958. SetValueAction.prototype._prepare = function () {
  48959. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48960. this._property = this._getProperty(this.propertyPath);
  48961. };
  48962. SetValueAction.prototype.execute = function () {
  48963. this._effectiveTarget[this._property] = this.value;
  48964. if (this._target.markAsDirty) {
  48965. this._target.markAsDirty(this._property);
  48966. }
  48967. };
  48968. SetValueAction.prototype.serialize = function (parent) {
  48969. return _super.prototype._serialize.call(this, {
  48970. name: "SetValueAction",
  48971. properties: [
  48972. BABYLON.Action._GetTargetProperty(this._target),
  48973. { name: "propertyPath", value: this.propertyPath },
  48974. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48975. ]
  48976. }, parent);
  48977. };
  48978. return SetValueAction;
  48979. }(BABYLON.Action));
  48980. BABYLON.SetValueAction = SetValueAction;
  48981. var IncrementValueAction = /** @class */ (function (_super) {
  48982. __extends(IncrementValueAction, _super);
  48983. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48984. var _this = _super.call(this, triggerOptions, condition) || this;
  48985. _this.propertyPath = propertyPath;
  48986. _this.value = value;
  48987. _this._target = _this._effectiveTarget = target;
  48988. return _this;
  48989. }
  48990. IncrementValueAction.prototype._prepare = function () {
  48991. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48992. this._property = this._getProperty(this.propertyPath);
  48993. if (typeof this._effectiveTarget[this._property] !== "number") {
  48994. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48995. }
  48996. };
  48997. IncrementValueAction.prototype.execute = function () {
  48998. this._effectiveTarget[this._property] += this.value;
  48999. if (this._target.markAsDirty) {
  49000. this._target.markAsDirty(this._property);
  49001. }
  49002. };
  49003. IncrementValueAction.prototype.serialize = function (parent) {
  49004. return _super.prototype._serialize.call(this, {
  49005. name: "IncrementValueAction",
  49006. properties: [
  49007. BABYLON.Action._GetTargetProperty(this._target),
  49008. { name: "propertyPath", value: this.propertyPath },
  49009. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49010. ]
  49011. }, parent);
  49012. };
  49013. return IncrementValueAction;
  49014. }(BABYLON.Action));
  49015. BABYLON.IncrementValueAction = IncrementValueAction;
  49016. var PlayAnimationAction = /** @class */ (function (_super) {
  49017. __extends(PlayAnimationAction, _super);
  49018. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49019. var _this = _super.call(this, triggerOptions, condition) || this;
  49020. _this.from = from;
  49021. _this.to = to;
  49022. _this.loop = loop;
  49023. _this._target = target;
  49024. return _this;
  49025. }
  49026. PlayAnimationAction.prototype._prepare = function () {
  49027. };
  49028. PlayAnimationAction.prototype.execute = function () {
  49029. var scene = this._actionManager.getScene();
  49030. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49031. };
  49032. PlayAnimationAction.prototype.serialize = function (parent) {
  49033. return _super.prototype._serialize.call(this, {
  49034. name: "PlayAnimationAction",
  49035. properties: [
  49036. BABYLON.Action._GetTargetProperty(this._target),
  49037. { name: "from", value: String(this.from) },
  49038. { name: "to", value: String(this.to) },
  49039. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49040. ]
  49041. }, parent);
  49042. };
  49043. return PlayAnimationAction;
  49044. }(BABYLON.Action));
  49045. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49046. var StopAnimationAction = /** @class */ (function (_super) {
  49047. __extends(StopAnimationAction, _super);
  49048. function StopAnimationAction(triggerOptions, target, condition) {
  49049. var _this = _super.call(this, triggerOptions, condition) || this;
  49050. _this._target = target;
  49051. return _this;
  49052. }
  49053. StopAnimationAction.prototype._prepare = function () {
  49054. };
  49055. StopAnimationAction.prototype.execute = function () {
  49056. var scene = this._actionManager.getScene();
  49057. scene.stopAnimation(this._target);
  49058. };
  49059. StopAnimationAction.prototype.serialize = function (parent) {
  49060. return _super.prototype._serialize.call(this, {
  49061. name: "StopAnimationAction",
  49062. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49063. }, parent);
  49064. };
  49065. return StopAnimationAction;
  49066. }(BABYLON.Action));
  49067. BABYLON.StopAnimationAction = StopAnimationAction;
  49068. var DoNothingAction = /** @class */ (function (_super) {
  49069. __extends(DoNothingAction, _super);
  49070. function DoNothingAction(triggerOptions, condition) {
  49071. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49072. return _super.call(this, triggerOptions, condition) || this;
  49073. }
  49074. DoNothingAction.prototype.execute = function () {
  49075. };
  49076. DoNothingAction.prototype.serialize = function (parent) {
  49077. return _super.prototype._serialize.call(this, {
  49078. name: "DoNothingAction",
  49079. properties: []
  49080. }, parent);
  49081. };
  49082. return DoNothingAction;
  49083. }(BABYLON.Action));
  49084. BABYLON.DoNothingAction = DoNothingAction;
  49085. var CombineAction = /** @class */ (function (_super) {
  49086. __extends(CombineAction, _super);
  49087. function CombineAction(triggerOptions, children, condition) {
  49088. var _this = _super.call(this, triggerOptions, condition) || this;
  49089. _this.children = children;
  49090. return _this;
  49091. }
  49092. CombineAction.prototype._prepare = function () {
  49093. for (var index = 0; index < this.children.length; index++) {
  49094. this.children[index]._actionManager = this._actionManager;
  49095. this.children[index]._prepare();
  49096. }
  49097. };
  49098. CombineAction.prototype.execute = function (evt) {
  49099. for (var index = 0; index < this.children.length; index++) {
  49100. this.children[index].execute(evt);
  49101. }
  49102. };
  49103. CombineAction.prototype.serialize = function (parent) {
  49104. var serializationObject = _super.prototype._serialize.call(this, {
  49105. name: "CombineAction",
  49106. properties: [],
  49107. combine: []
  49108. }, parent);
  49109. for (var i = 0; i < this.children.length; i++) {
  49110. serializationObject.combine.push(this.children[i].serialize(null));
  49111. }
  49112. return serializationObject;
  49113. };
  49114. return CombineAction;
  49115. }(BABYLON.Action));
  49116. BABYLON.CombineAction = CombineAction;
  49117. var ExecuteCodeAction = /** @class */ (function (_super) {
  49118. __extends(ExecuteCodeAction, _super);
  49119. function ExecuteCodeAction(triggerOptions, func, condition) {
  49120. var _this = _super.call(this, triggerOptions, condition) || this;
  49121. _this.func = func;
  49122. return _this;
  49123. }
  49124. ExecuteCodeAction.prototype.execute = function (evt) {
  49125. this.func(evt);
  49126. };
  49127. return ExecuteCodeAction;
  49128. }(BABYLON.Action));
  49129. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49130. var SetParentAction = /** @class */ (function (_super) {
  49131. __extends(SetParentAction, _super);
  49132. function SetParentAction(triggerOptions, target, parent, condition) {
  49133. var _this = _super.call(this, triggerOptions, condition) || this;
  49134. _this._target = target;
  49135. _this._parent = parent;
  49136. return _this;
  49137. }
  49138. SetParentAction.prototype._prepare = function () {
  49139. };
  49140. SetParentAction.prototype.execute = function () {
  49141. if (this._target.parent === this._parent) {
  49142. return;
  49143. }
  49144. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49145. invertParentWorldMatrix.invert();
  49146. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49147. this._target.parent = this._parent;
  49148. };
  49149. SetParentAction.prototype.serialize = function (parent) {
  49150. return _super.prototype._serialize.call(this, {
  49151. name: "SetParentAction",
  49152. properties: [
  49153. BABYLON.Action._GetTargetProperty(this._target),
  49154. BABYLON.Action._GetTargetProperty(this._parent),
  49155. ]
  49156. }, parent);
  49157. };
  49158. return SetParentAction;
  49159. }(BABYLON.Action));
  49160. BABYLON.SetParentAction = SetParentAction;
  49161. var PlaySoundAction = /** @class */ (function (_super) {
  49162. __extends(PlaySoundAction, _super);
  49163. function PlaySoundAction(triggerOptions, sound, condition) {
  49164. var _this = _super.call(this, triggerOptions, condition) || this;
  49165. _this._sound = sound;
  49166. return _this;
  49167. }
  49168. PlaySoundAction.prototype._prepare = function () {
  49169. };
  49170. PlaySoundAction.prototype.execute = function () {
  49171. if (this._sound !== undefined)
  49172. this._sound.play();
  49173. };
  49174. PlaySoundAction.prototype.serialize = function (parent) {
  49175. return _super.prototype._serialize.call(this, {
  49176. name: "PlaySoundAction",
  49177. properties: [{ name: "sound", value: this._sound.name }]
  49178. }, parent);
  49179. };
  49180. return PlaySoundAction;
  49181. }(BABYLON.Action));
  49182. BABYLON.PlaySoundAction = PlaySoundAction;
  49183. var StopSoundAction = /** @class */ (function (_super) {
  49184. __extends(StopSoundAction, _super);
  49185. function StopSoundAction(triggerOptions, sound, condition) {
  49186. var _this = _super.call(this, triggerOptions, condition) || this;
  49187. _this._sound = sound;
  49188. return _this;
  49189. }
  49190. StopSoundAction.prototype._prepare = function () {
  49191. };
  49192. StopSoundAction.prototype.execute = function () {
  49193. if (this._sound !== undefined)
  49194. this._sound.stop();
  49195. };
  49196. StopSoundAction.prototype.serialize = function (parent) {
  49197. return _super.prototype._serialize.call(this, {
  49198. name: "StopSoundAction",
  49199. properties: [{ name: "sound", value: this._sound.name }]
  49200. }, parent);
  49201. };
  49202. return StopSoundAction;
  49203. }(BABYLON.Action));
  49204. BABYLON.StopSoundAction = StopSoundAction;
  49205. })(BABYLON || (BABYLON = {}));
  49206. //# sourceMappingURL=babylon.directActions.js.map
  49207. var BABYLON;
  49208. (function (BABYLON) {
  49209. var SpriteManager = /** @class */ (function () {
  49210. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49211. if (epsilon === void 0) { epsilon = 0.01; }
  49212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49213. this.name = name;
  49214. this.sprites = new Array();
  49215. this.renderingGroupId = 0;
  49216. this.layerMask = 0x0FFFFFFF;
  49217. this.fogEnabled = true;
  49218. this.isPickable = false;
  49219. /**
  49220. * An event triggered when the manager is disposed.
  49221. * @type {BABYLON.Observable}
  49222. */
  49223. this.onDisposeObservable = new BABYLON.Observable();
  49224. this._vertexBuffers = {};
  49225. this._capacity = capacity;
  49226. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49227. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49228. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49229. if (cellSize.width && cellSize.height) {
  49230. this.cellWidth = cellSize.width;
  49231. this.cellHeight = cellSize.height;
  49232. }
  49233. else if (cellSize !== undefined) {
  49234. this.cellWidth = cellSize;
  49235. this.cellHeight = cellSize;
  49236. }
  49237. else {
  49238. return;
  49239. }
  49240. this._epsilon = epsilon;
  49241. this._scene = scene;
  49242. this._scene.spriteManagers.push(this);
  49243. var indices = [];
  49244. var index = 0;
  49245. for (var count = 0; count < capacity; count++) {
  49246. indices.push(index);
  49247. indices.push(index + 1);
  49248. indices.push(index + 2);
  49249. indices.push(index);
  49250. indices.push(index + 2);
  49251. indices.push(index + 3);
  49252. index += 4;
  49253. }
  49254. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49255. // VBO
  49256. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49257. this._vertexData = new Float32Array(capacity * 16 * 4);
  49258. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49259. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49260. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49261. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49262. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49263. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49264. this._vertexBuffers["options"] = options;
  49265. this._vertexBuffers["cellInfo"] = cellInfo;
  49266. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49267. // Effects
  49268. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49269. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49270. }
  49271. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49272. set: function (callback) {
  49273. if (this._onDisposeObserver) {
  49274. this.onDisposeObservable.remove(this._onDisposeObserver);
  49275. }
  49276. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49277. },
  49278. enumerable: true,
  49279. configurable: true
  49280. });
  49281. Object.defineProperty(SpriteManager.prototype, "texture", {
  49282. get: function () {
  49283. return this._spriteTexture;
  49284. },
  49285. set: function (value) {
  49286. this._spriteTexture = value;
  49287. },
  49288. enumerable: true,
  49289. configurable: true
  49290. });
  49291. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49292. var arrayOffset = index * 16;
  49293. if (offsetX === 0)
  49294. offsetX = this._epsilon;
  49295. else if (offsetX === 1)
  49296. offsetX = 1 - this._epsilon;
  49297. if (offsetY === 0)
  49298. offsetY = this._epsilon;
  49299. else if (offsetY === 1)
  49300. offsetY = 1 - this._epsilon;
  49301. this._vertexData[arrayOffset] = sprite.position.x;
  49302. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49303. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49304. this._vertexData[arrayOffset + 3] = sprite.angle;
  49305. this._vertexData[arrayOffset + 4] = sprite.width;
  49306. this._vertexData[arrayOffset + 5] = sprite.height;
  49307. this._vertexData[arrayOffset + 6] = offsetX;
  49308. this._vertexData[arrayOffset + 7] = offsetY;
  49309. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49310. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49311. var offset = (sprite.cellIndex / rowSize) >> 0;
  49312. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49313. this._vertexData[arrayOffset + 11] = offset;
  49314. // Color
  49315. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49316. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49317. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49318. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49319. };
  49320. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49321. var count = Math.min(this._capacity, this.sprites.length);
  49322. var min = BABYLON.Vector3.Zero();
  49323. var max = BABYLON.Vector3.Zero();
  49324. var distance = Number.MAX_VALUE;
  49325. var currentSprite = null;
  49326. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49327. var cameraView = camera.getViewMatrix();
  49328. for (var index = 0; index < count; index++) {
  49329. var sprite = this.sprites[index];
  49330. if (!sprite) {
  49331. continue;
  49332. }
  49333. if (predicate) {
  49334. if (!predicate(sprite)) {
  49335. continue;
  49336. }
  49337. }
  49338. else if (!sprite.isPickable) {
  49339. continue;
  49340. }
  49341. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49342. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49343. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49344. if (ray.intersectsBoxMinMax(min, max)) {
  49345. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49346. if (distance > currentDistance) {
  49347. distance = currentDistance;
  49348. currentSprite = sprite;
  49349. if (fastCheck) {
  49350. break;
  49351. }
  49352. }
  49353. }
  49354. }
  49355. if (currentSprite) {
  49356. var result = new BABYLON.PickingInfo();
  49357. result.hit = true;
  49358. result.pickedSprite = currentSprite;
  49359. result.distance = distance;
  49360. return result;
  49361. }
  49362. return null;
  49363. };
  49364. SpriteManager.prototype.render = function () {
  49365. // Check
  49366. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49367. return;
  49368. var engine = this._scene.getEngine();
  49369. var baseSize = this._spriteTexture.getBaseSize();
  49370. // Sprites
  49371. var deltaTime = engine.getDeltaTime();
  49372. var max = Math.min(this._capacity, this.sprites.length);
  49373. var rowSize = baseSize.width / this.cellWidth;
  49374. var offset = 0;
  49375. for (var index = 0; index < max; index++) {
  49376. var sprite = this.sprites[index];
  49377. if (!sprite) {
  49378. continue;
  49379. }
  49380. sprite._animate(deltaTime);
  49381. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49382. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49383. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49384. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49385. }
  49386. this._buffer.update(this._vertexData);
  49387. // Render
  49388. var effect = this._effectBase;
  49389. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49390. effect = this._effectFog;
  49391. }
  49392. engine.enableEffect(effect);
  49393. var viewMatrix = this._scene.getViewMatrix();
  49394. effect.setTexture("diffuseSampler", this._spriteTexture);
  49395. effect.setMatrix("view", viewMatrix);
  49396. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49397. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49398. // Fog
  49399. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49400. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49401. effect.setColor3("vFogColor", this._scene.fogColor);
  49402. }
  49403. // VBOs
  49404. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49405. // Draw order
  49406. engine.setDepthFunctionToLessOrEqual();
  49407. effect.setBool("alphaTest", true);
  49408. engine.setColorWrite(false);
  49409. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49410. engine.setColorWrite(true);
  49411. effect.setBool("alphaTest", false);
  49412. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49413. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49414. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49415. };
  49416. SpriteManager.prototype.dispose = function () {
  49417. if (this._buffer) {
  49418. this._buffer.dispose();
  49419. this._buffer = null;
  49420. }
  49421. if (this._indexBuffer) {
  49422. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49423. this._indexBuffer = null;
  49424. }
  49425. if (this._spriteTexture) {
  49426. this._spriteTexture.dispose();
  49427. this._spriteTexture = null;
  49428. }
  49429. // Remove from scene
  49430. var index = this._scene.spriteManagers.indexOf(this);
  49431. this._scene.spriteManagers.splice(index, 1);
  49432. // Callback
  49433. this.onDisposeObservable.notifyObservers(this);
  49434. this.onDisposeObservable.clear();
  49435. };
  49436. return SpriteManager;
  49437. }());
  49438. BABYLON.SpriteManager = SpriteManager;
  49439. })(BABYLON || (BABYLON = {}));
  49440. //# sourceMappingURL=babylon.spriteManager.js.map
  49441. var BABYLON;
  49442. (function (BABYLON) {
  49443. var Sprite = /** @class */ (function () {
  49444. function Sprite(name, manager) {
  49445. this.name = name;
  49446. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49447. this.width = 1.0;
  49448. this.height = 1.0;
  49449. this.angle = 0;
  49450. this.cellIndex = 0;
  49451. this.invertU = 0;
  49452. this.invertV = 0;
  49453. this.animations = new Array();
  49454. this.isPickable = false;
  49455. this._animationStarted = false;
  49456. this._loopAnimation = false;
  49457. this._fromIndex = 0;
  49458. this._toIndex = 0;
  49459. this._delay = 0;
  49460. this._direction = 1;
  49461. this._time = 0;
  49462. this._manager = manager;
  49463. this._manager.sprites.push(this);
  49464. this.position = BABYLON.Vector3.Zero();
  49465. }
  49466. Object.defineProperty(Sprite.prototype, "size", {
  49467. get: function () {
  49468. return this.width;
  49469. },
  49470. set: function (value) {
  49471. this.width = value;
  49472. this.height = value;
  49473. },
  49474. enumerable: true,
  49475. configurable: true
  49476. });
  49477. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49478. this._fromIndex = from;
  49479. this._toIndex = to;
  49480. this._loopAnimation = loop;
  49481. this._delay = delay;
  49482. this._animationStarted = true;
  49483. this._direction = from < to ? 1 : -1;
  49484. this.cellIndex = from;
  49485. this._time = 0;
  49486. this._onAnimationEnd = onAnimationEnd;
  49487. };
  49488. Sprite.prototype.stopAnimation = function () {
  49489. this._animationStarted = false;
  49490. };
  49491. Sprite.prototype._animate = function (deltaTime) {
  49492. if (!this._animationStarted)
  49493. return;
  49494. this._time += deltaTime;
  49495. if (this._time > this._delay) {
  49496. this._time = this._time % this._delay;
  49497. this.cellIndex += this._direction;
  49498. if (this.cellIndex > this._toIndex) {
  49499. if (this._loopAnimation) {
  49500. this.cellIndex = this._fromIndex;
  49501. }
  49502. else {
  49503. this.cellIndex = this._toIndex;
  49504. this._animationStarted = false;
  49505. if (this._onAnimationEnd) {
  49506. this._onAnimationEnd();
  49507. }
  49508. if (this.disposeWhenFinishedAnimating) {
  49509. this.dispose();
  49510. }
  49511. }
  49512. }
  49513. }
  49514. };
  49515. Sprite.prototype.dispose = function () {
  49516. for (var i = 0; i < this._manager.sprites.length; i++) {
  49517. if (this._manager.sprites[i] == this) {
  49518. this._manager.sprites.splice(i, 1);
  49519. }
  49520. }
  49521. };
  49522. return Sprite;
  49523. }());
  49524. BABYLON.Sprite = Sprite;
  49525. })(BABYLON || (BABYLON = {}));
  49526. //# sourceMappingURL=babylon.sprite.js.map
  49527. var BABYLON;
  49528. (function (BABYLON) {
  49529. var IntersectionInfo = /** @class */ (function () {
  49530. function IntersectionInfo(bu, bv, distance) {
  49531. this.bu = bu;
  49532. this.bv = bv;
  49533. this.distance = distance;
  49534. this.faceId = 0;
  49535. this.subMeshId = 0;
  49536. }
  49537. return IntersectionInfo;
  49538. }());
  49539. BABYLON.IntersectionInfo = IntersectionInfo;
  49540. var PickingInfo = /** @class */ (function () {
  49541. function PickingInfo() {
  49542. this.hit = false;
  49543. this.distance = 0;
  49544. this.pickedPoint = null;
  49545. this.pickedMesh = null;
  49546. this.bu = 0;
  49547. this.bv = 0;
  49548. this.faceId = -1;
  49549. this.subMeshId = 0;
  49550. this.pickedSprite = null;
  49551. }
  49552. // Methods
  49553. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49554. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49555. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49556. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49557. return null;
  49558. }
  49559. var indices = this.pickedMesh.getIndices();
  49560. if (!indices) {
  49561. return null;
  49562. }
  49563. var result;
  49564. if (useVerticesNormals) {
  49565. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49566. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49567. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49568. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49569. normal0 = normal0.scale(this.bu);
  49570. normal1 = normal1.scale(this.bv);
  49571. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49572. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49573. }
  49574. else {
  49575. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49576. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49577. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49578. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49579. var p1p2 = vertex1.subtract(vertex2);
  49580. var p3p2 = vertex3.subtract(vertex2);
  49581. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49582. }
  49583. if (useWorldCoordinates) {
  49584. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49585. }
  49586. return BABYLON.Vector3.Normalize(result);
  49587. };
  49588. PickingInfo.prototype.getTextureCoordinates = function () {
  49589. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49590. return null;
  49591. }
  49592. var indices = this.pickedMesh.getIndices();
  49593. if (!indices) {
  49594. return null;
  49595. }
  49596. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49597. if (!uvs) {
  49598. return null;
  49599. }
  49600. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49601. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49602. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49603. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49604. uv1 = uv1.scale(this.bu);
  49605. uv2 = uv2.scale(this.bv);
  49606. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49607. };
  49608. return PickingInfo;
  49609. }());
  49610. BABYLON.PickingInfo = PickingInfo;
  49611. })(BABYLON || (BABYLON = {}));
  49612. //# sourceMappingURL=babylon.pickingInfo.js.map
  49613. var BABYLON;
  49614. (function (BABYLON) {
  49615. var Ray = /** @class */ (function () {
  49616. function Ray(origin, direction, length) {
  49617. if (length === void 0) { length = Number.MAX_VALUE; }
  49618. this.origin = origin;
  49619. this.direction = direction;
  49620. this.length = length;
  49621. }
  49622. // Methods
  49623. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49624. var d = 0.0;
  49625. var maxValue = Number.MAX_VALUE;
  49626. var inv;
  49627. var min;
  49628. var max;
  49629. var temp;
  49630. if (Math.abs(this.direction.x) < 0.0000001) {
  49631. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49632. return false;
  49633. }
  49634. }
  49635. else {
  49636. inv = 1.0 / this.direction.x;
  49637. min = (minimum.x - this.origin.x) * inv;
  49638. max = (maximum.x - this.origin.x) * inv;
  49639. if (max === -Infinity) {
  49640. max = Infinity;
  49641. }
  49642. if (min > max) {
  49643. temp = min;
  49644. min = max;
  49645. max = temp;
  49646. }
  49647. d = Math.max(min, d);
  49648. maxValue = Math.min(max, maxValue);
  49649. if (d > maxValue) {
  49650. return false;
  49651. }
  49652. }
  49653. if (Math.abs(this.direction.y) < 0.0000001) {
  49654. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49655. return false;
  49656. }
  49657. }
  49658. else {
  49659. inv = 1.0 / this.direction.y;
  49660. min = (minimum.y - this.origin.y) * inv;
  49661. max = (maximum.y - this.origin.y) * inv;
  49662. if (max === -Infinity) {
  49663. max = Infinity;
  49664. }
  49665. if (min > max) {
  49666. temp = min;
  49667. min = max;
  49668. max = temp;
  49669. }
  49670. d = Math.max(min, d);
  49671. maxValue = Math.min(max, maxValue);
  49672. if (d > maxValue) {
  49673. return false;
  49674. }
  49675. }
  49676. if (Math.abs(this.direction.z) < 0.0000001) {
  49677. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49678. return false;
  49679. }
  49680. }
  49681. else {
  49682. inv = 1.0 / this.direction.z;
  49683. min = (minimum.z - this.origin.z) * inv;
  49684. max = (maximum.z - this.origin.z) * 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. return true;
  49700. };
  49701. Ray.prototype.intersectsBox = function (box) {
  49702. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49703. };
  49704. Ray.prototype.intersectsSphere = function (sphere) {
  49705. var x = sphere.center.x - this.origin.x;
  49706. var y = sphere.center.y - this.origin.y;
  49707. var z = sphere.center.z - this.origin.z;
  49708. var pyth = (x * x) + (y * y) + (z * z);
  49709. var rr = sphere.radius * sphere.radius;
  49710. if (pyth <= rr) {
  49711. return true;
  49712. }
  49713. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49714. if (dot < 0.0) {
  49715. return false;
  49716. }
  49717. var temp = pyth - (dot * dot);
  49718. return temp <= rr;
  49719. };
  49720. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49721. if (!this._edge1) {
  49722. this._edge1 = BABYLON.Vector3.Zero();
  49723. this._edge2 = BABYLON.Vector3.Zero();
  49724. this._pvec = BABYLON.Vector3.Zero();
  49725. this._tvec = BABYLON.Vector3.Zero();
  49726. this._qvec = BABYLON.Vector3.Zero();
  49727. }
  49728. vertex1.subtractToRef(vertex0, this._edge1);
  49729. vertex2.subtractToRef(vertex0, this._edge2);
  49730. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49731. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49732. if (det === 0) {
  49733. return null;
  49734. }
  49735. var invdet = 1 / det;
  49736. this.origin.subtractToRef(vertex0, this._tvec);
  49737. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49738. if (bu < 0 || bu > 1.0) {
  49739. return null;
  49740. }
  49741. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49742. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49743. if (bv < 0 || bu + bv > 1.0) {
  49744. return null;
  49745. }
  49746. //check if the distance is longer than the predefined length.
  49747. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49748. if (distance > this.length) {
  49749. return null;
  49750. }
  49751. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49752. };
  49753. Ray.prototype.intersectsPlane = function (plane) {
  49754. var distance;
  49755. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49756. if (Math.abs(result1) < 9.99999997475243E-07) {
  49757. return null;
  49758. }
  49759. else {
  49760. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49761. distance = (-plane.d - result2) / result1;
  49762. if (distance < 0.0) {
  49763. if (distance < -9.99999997475243E-07) {
  49764. return null;
  49765. }
  49766. else {
  49767. return 0;
  49768. }
  49769. }
  49770. return distance;
  49771. }
  49772. };
  49773. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49774. var tm = BABYLON.Tmp.Matrix[0];
  49775. mesh.getWorldMatrix().invertToRef(tm);
  49776. if (this._tmpRay) {
  49777. Ray.TransformToRef(this, tm, this._tmpRay);
  49778. }
  49779. else {
  49780. this._tmpRay = Ray.Transform(this, tm);
  49781. }
  49782. return mesh.intersects(this._tmpRay, fastCheck);
  49783. };
  49784. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49785. if (results) {
  49786. results.length = 0;
  49787. }
  49788. else {
  49789. results = [];
  49790. }
  49791. for (var i = 0; i < meshes.length; i++) {
  49792. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49793. if (pickInfo.hit) {
  49794. results.push(pickInfo);
  49795. }
  49796. }
  49797. results.sort(this._comparePickingInfo);
  49798. return results;
  49799. };
  49800. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49801. if (pickingInfoA.distance < pickingInfoB.distance) {
  49802. return -1;
  49803. }
  49804. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49805. return 1;
  49806. }
  49807. else {
  49808. return 0;
  49809. }
  49810. };
  49811. /**
  49812. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49813. * @param sega the first point of the segment to test the intersection against
  49814. * @param segb the second point of the segment to test the intersection against
  49815. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49816. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49817. */
  49818. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49819. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49820. var u = segb.subtract(sega);
  49821. var v = rsegb.subtract(this.origin);
  49822. var w = sega.subtract(this.origin);
  49823. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49824. var b = BABYLON.Vector3.Dot(u, v);
  49825. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49826. var d = BABYLON.Vector3.Dot(u, w);
  49827. var e = BABYLON.Vector3.Dot(v, w);
  49828. var D = a * c - b * b; // always >= 0
  49829. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49830. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49831. // compute the line parameters of the two closest points
  49832. if (D < Ray.smallnum) {
  49833. sN = 0.0; // force using point P0 on segment S1
  49834. sD = 1.0; // to prevent possible division by 0.0 later
  49835. tN = e;
  49836. tD = c;
  49837. }
  49838. else {
  49839. sN = (b * e - c * d);
  49840. tN = (a * e - b * d);
  49841. if (sN < 0.0) {
  49842. sN = 0.0;
  49843. tN = e;
  49844. tD = c;
  49845. }
  49846. else if (sN > sD) {
  49847. sN = sD;
  49848. tN = e + b;
  49849. tD = c;
  49850. }
  49851. }
  49852. if (tN < 0.0) {
  49853. tN = 0.0;
  49854. // recompute sc for this edge
  49855. if (-d < 0.0) {
  49856. sN = 0.0;
  49857. }
  49858. else if (-d > a)
  49859. sN = sD;
  49860. else {
  49861. sN = -d;
  49862. sD = a;
  49863. }
  49864. }
  49865. else if (tN > tD) {
  49866. tN = tD;
  49867. // recompute sc for this edge
  49868. if ((-d + b) < 0.0) {
  49869. sN = 0;
  49870. }
  49871. else if ((-d + b) > a) {
  49872. sN = sD;
  49873. }
  49874. else {
  49875. sN = (-d + b);
  49876. sD = a;
  49877. }
  49878. }
  49879. // finally do the division to get sc and tc
  49880. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49881. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49882. // get the difference of the two closest points
  49883. var qtc = v.multiplyByFloats(tc, tc, tc);
  49884. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49885. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49886. if (isIntersected) {
  49887. return qtc.length();
  49888. }
  49889. return -1;
  49890. };
  49891. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49892. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49893. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49894. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49895. this.direction.normalize();
  49896. return this;
  49897. };
  49898. // Statics
  49899. Ray.Zero = function () {
  49900. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49901. };
  49902. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49903. var result = Ray.Zero();
  49904. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49905. };
  49906. /**
  49907. * 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
  49908. * transformed to the given world matrix.
  49909. * @param origin The origin point
  49910. * @param end The end point
  49911. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49912. */
  49913. Ray.CreateNewFromTo = function (origin, end, world) {
  49914. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49915. var direction = end.subtract(origin);
  49916. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49917. direction.normalize();
  49918. return Ray.Transform(new Ray(origin, direction, length), world);
  49919. };
  49920. Ray.Transform = function (ray, matrix) {
  49921. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49922. Ray.TransformToRef(ray, matrix, result);
  49923. return result;
  49924. };
  49925. Ray.TransformToRef = function (ray, matrix, result) {
  49926. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49927. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49928. result.length = ray.length;
  49929. var dir = result.direction;
  49930. var len = dir.length();
  49931. if (!(len === 0 || len === 1)) {
  49932. var num = 1.0 / len;
  49933. dir.x *= num;
  49934. dir.y *= num;
  49935. dir.z *= num;
  49936. result.length *= len;
  49937. }
  49938. };
  49939. Ray.smallnum = 0.00000001;
  49940. Ray.rayl = 10e8;
  49941. return Ray;
  49942. }());
  49943. BABYLON.Ray = Ray;
  49944. })(BABYLON || (BABYLON = {}));
  49945. //# sourceMappingURL=babylon.ray.js.map
  49946. var BABYLON;
  49947. (function (BABYLON) {
  49948. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49949. if (boxMin.x > sphereCenter.x + sphereRadius)
  49950. return false;
  49951. if (sphereCenter.x - sphereRadius > boxMax.x)
  49952. return false;
  49953. if (boxMin.y > sphereCenter.y + sphereRadius)
  49954. return false;
  49955. if (sphereCenter.y - sphereRadius > boxMax.y)
  49956. return false;
  49957. if (boxMin.z > sphereCenter.z + sphereRadius)
  49958. return false;
  49959. if (sphereCenter.z - sphereRadius > boxMax.z)
  49960. return false;
  49961. return true;
  49962. };
  49963. var getLowestRoot = (function () {
  49964. var result = { root: 0, found: false };
  49965. return function (a, b, c, maxR) {
  49966. result.root = 0;
  49967. result.found = false;
  49968. var determinant = b * b - 4.0 * a * c;
  49969. if (determinant < 0)
  49970. return result;
  49971. var sqrtD = Math.sqrt(determinant);
  49972. var r1 = (-b - sqrtD) / (2.0 * a);
  49973. var r2 = (-b + sqrtD) / (2.0 * a);
  49974. if (r1 > r2) {
  49975. var temp = r2;
  49976. r2 = r1;
  49977. r1 = temp;
  49978. }
  49979. if (r1 > 0 && r1 < maxR) {
  49980. result.root = r1;
  49981. result.found = true;
  49982. return result;
  49983. }
  49984. if (r2 > 0 && r2 < maxR) {
  49985. result.root = r2;
  49986. result.found = true;
  49987. return result;
  49988. }
  49989. return result;
  49990. };
  49991. })();
  49992. var Collider = /** @class */ (function () {
  49993. function Collider() {
  49994. this._collisionPoint = BABYLON.Vector3.Zero();
  49995. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49996. this._tempVector = BABYLON.Vector3.Zero();
  49997. this._tempVector2 = BABYLON.Vector3.Zero();
  49998. this._tempVector3 = BABYLON.Vector3.Zero();
  49999. this._tempVector4 = BABYLON.Vector3.Zero();
  50000. this._edge = BABYLON.Vector3.Zero();
  50001. this._baseToVertex = BABYLON.Vector3.Zero();
  50002. this._destinationPoint = BABYLON.Vector3.Zero();
  50003. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50004. this._displacementVector = BABYLON.Vector3.Zero();
  50005. this._radius = BABYLON.Vector3.One();
  50006. this._retry = 0;
  50007. this._basePointWorld = BABYLON.Vector3.Zero();
  50008. this._velocityWorld = BABYLON.Vector3.Zero();
  50009. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50010. this._collisionMask = -1;
  50011. }
  50012. Object.defineProperty(Collider.prototype, "collisionMask", {
  50013. get: function () {
  50014. return this._collisionMask;
  50015. },
  50016. set: function (mask) {
  50017. this._collisionMask = !isNaN(mask) ? mask : -1;
  50018. },
  50019. enumerable: true,
  50020. configurable: true
  50021. });
  50022. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50023. /**
  50024. * Gets the plane normal used to compute the sliding response (in local space)
  50025. */
  50026. get: function () {
  50027. return this._slidePlaneNormal;
  50028. },
  50029. enumerable: true,
  50030. configurable: true
  50031. });
  50032. // Methods
  50033. Collider.prototype._initialize = function (source, dir, e) {
  50034. this._velocity = dir;
  50035. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50036. this._basePoint = source;
  50037. source.multiplyToRef(this._radius, this._basePointWorld);
  50038. dir.multiplyToRef(this._radius, this._velocityWorld);
  50039. this._velocityWorldLength = this._velocityWorld.length();
  50040. this._epsilon = e;
  50041. this.collisionFound = false;
  50042. };
  50043. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50044. pa.subtractToRef(point, this._tempVector);
  50045. pb.subtractToRef(point, this._tempVector2);
  50046. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50047. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50048. if (d < 0)
  50049. return false;
  50050. pc.subtractToRef(point, this._tempVector3);
  50051. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50052. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50053. if (d < 0)
  50054. return false;
  50055. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50056. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50057. return d >= 0;
  50058. };
  50059. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50060. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50061. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50062. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50063. return false;
  50064. }
  50065. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50066. return false;
  50067. return true;
  50068. };
  50069. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50070. var t0;
  50071. var embeddedInPlane = false;
  50072. //defensive programming, actually not needed.
  50073. if (!trianglePlaneArray) {
  50074. trianglePlaneArray = [];
  50075. }
  50076. if (!trianglePlaneArray[faceIndex]) {
  50077. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50078. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50079. }
  50080. var trianglePlane = trianglePlaneArray[faceIndex];
  50081. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50082. return;
  50083. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50084. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50085. if (normalDotVelocity == 0) {
  50086. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50087. return;
  50088. embeddedInPlane = true;
  50089. t0 = 0;
  50090. }
  50091. else {
  50092. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50093. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50094. if (t0 > t1) {
  50095. var temp = t1;
  50096. t1 = t0;
  50097. t0 = temp;
  50098. }
  50099. if (t0 > 1.0 || t1 < 0.0)
  50100. return;
  50101. if (t0 < 0)
  50102. t0 = 0;
  50103. if (t0 > 1.0)
  50104. t0 = 1.0;
  50105. }
  50106. this._collisionPoint.copyFromFloats(0, 0, 0);
  50107. var found = false;
  50108. var t = 1.0;
  50109. if (!embeddedInPlane) {
  50110. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50111. this._velocity.scaleToRef(t0, this._tempVector);
  50112. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50113. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50114. found = true;
  50115. t = t0;
  50116. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50117. }
  50118. }
  50119. if (!found) {
  50120. var velocitySquaredLength = this._velocity.lengthSquared();
  50121. var a = velocitySquaredLength;
  50122. this._basePoint.subtractToRef(p1, this._tempVector);
  50123. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50124. var c = this._tempVector.lengthSquared() - 1.0;
  50125. var lowestRoot = getLowestRoot(a, b, c, t);
  50126. if (lowestRoot.found) {
  50127. t = lowestRoot.root;
  50128. found = true;
  50129. this._collisionPoint.copyFrom(p1);
  50130. }
  50131. this._basePoint.subtractToRef(p2, this._tempVector);
  50132. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50133. c = this._tempVector.lengthSquared() - 1.0;
  50134. lowestRoot = getLowestRoot(a, b, c, t);
  50135. if (lowestRoot.found) {
  50136. t = lowestRoot.root;
  50137. found = true;
  50138. this._collisionPoint.copyFrom(p2);
  50139. }
  50140. this._basePoint.subtractToRef(p3, this._tempVector);
  50141. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50142. c = this._tempVector.lengthSquared() - 1.0;
  50143. lowestRoot = getLowestRoot(a, b, c, t);
  50144. if (lowestRoot.found) {
  50145. t = lowestRoot.root;
  50146. found = true;
  50147. this._collisionPoint.copyFrom(p3);
  50148. }
  50149. p2.subtractToRef(p1, this._edge);
  50150. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50151. var edgeSquaredLength = this._edge.lengthSquared();
  50152. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50153. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50154. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50155. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50156. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50157. lowestRoot = getLowestRoot(a, b, c, t);
  50158. if (lowestRoot.found) {
  50159. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50160. if (f >= 0.0 && f <= 1.0) {
  50161. t = lowestRoot.root;
  50162. found = true;
  50163. this._edge.scaleInPlace(f);
  50164. p1.addToRef(this._edge, this._collisionPoint);
  50165. }
  50166. }
  50167. p3.subtractToRef(p2, this._edge);
  50168. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50169. edgeSquaredLength = this._edge.lengthSquared();
  50170. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50171. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50172. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50173. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50174. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50175. lowestRoot = getLowestRoot(a, b, c, t);
  50176. if (lowestRoot.found) {
  50177. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50178. if (f >= 0.0 && f <= 1.0) {
  50179. t = lowestRoot.root;
  50180. found = true;
  50181. this._edge.scaleInPlace(f);
  50182. p2.addToRef(this._edge, this._collisionPoint);
  50183. }
  50184. }
  50185. p1.subtractToRef(p3, this._edge);
  50186. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50187. edgeSquaredLength = this._edge.lengthSquared();
  50188. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50189. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50190. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50191. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50192. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50193. lowestRoot = getLowestRoot(a, b, c, t);
  50194. if (lowestRoot.found) {
  50195. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50196. if (f >= 0.0 && f <= 1.0) {
  50197. t = lowestRoot.root;
  50198. found = true;
  50199. this._edge.scaleInPlace(f);
  50200. p3.addToRef(this._edge, this._collisionPoint);
  50201. }
  50202. }
  50203. }
  50204. if (found) {
  50205. var distToCollision = t * this._velocity.length();
  50206. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50207. if (!this.intersectionPoint) {
  50208. this.intersectionPoint = this._collisionPoint.clone();
  50209. }
  50210. else {
  50211. this.intersectionPoint.copyFrom(this._collisionPoint);
  50212. }
  50213. this._nearestDistance = distToCollision;
  50214. this.collisionFound = true;
  50215. }
  50216. }
  50217. };
  50218. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50219. for (var i = indexStart; i < indexEnd; i += 3) {
  50220. var p1 = pts[indices[i] - decal];
  50221. var p2 = pts[indices[i + 1] - decal];
  50222. var p3 = pts[indices[i + 2] - decal];
  50223. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50224. }
  50225. };
  50226. Collider.prototype._getResponse = function (pos, vel) {
  50227. pos.addToRef(vel, this._destinationPoint);
  50228. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50229. this._basePoint.addToRef(vel, pos);
  50230. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50231. this._slidePlaneNormal.normalize();
  50232. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50233. pos.addInPlace(this._displacementVector);
  50234. this.intersectionPoint.addInPlace(this._displacementVector);
  50235. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50236. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50237. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50238. };
  50239. return Collider;
  50240. }());
  50241. BABYLON.Collider = Collider;
  50242. })(BABYLON || (BABYLON = {}));
  50243. //# sourceMappingURL=babylon.collider.js.map
  50244. var BABYLON;
  50245. (function (BABYLON) {
  50246. //WebWorker code will be inserted to this variable.
  50247. BABYLON.CollisionWorker = "";
  50248. var WorkerTaskType;
  50249. (function (WorkerTaskType) {
  50250. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50251. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50252. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50253. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50254. var WorkerReplyType;
  50255. (function (WorkerReplyType) {
  50256. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50257. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50258. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50259. var CollisionCoordinatorWorker = /** @class */ (function () {
  50260. function CollisionCoordinatorWorker() {
  50261. var _this = this;
  50262. this._scaledPosition = BABYLON.Vector3.Zero();
  50263. this._scaledVelocity = BABYLON.Vector3.Zero();
  50264. this.onMeshUpdated = function (transformNode) {
  50265. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50266. };
  50267. this.onGeometryUpdated = function (geometry) {
  50268. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50269. };
  50270. this._afterRender = function () {
  50271. if (!_this._init)
  50272. return;
  50273. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50274. return;
  50275. }
  50276. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50277. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50278. if (_this._runningUpdated > 4) {
  50279. return;
  50280. }
  50281. ++_this._runningUpdated;
  50282. var payload = {
  50283. updatedMeshes: _this._addUpdateMeshesList,
  50284. updatedGeometries: _this._addUpdateGeometriesList,
  50285. removedGeometries: _this._toRemoveGeometryArray,
  50286. removedMeshes: _this._toRemoveMeshesArray
  50287. };
  50288. var message = {
  50289. payload: payload,
  50290. taskType: WorkerTaskType.UPDATE
  50291. };
  50292. var serializable = [];
  50293. for (var id in payload.updatedGeometries) {
  50294. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50295. //prepare transferables
  50296. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50297. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50298. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50299. }
  50300. }
  50301. _this._worker.postMessage(message, serializable);
  50302. _this._addUpdateMeshesList = {};
  50303. _this._addUpdateGeometriesList = {};
  50304. _this._toRemoveGeometryArray = [];
  50305. _this._toRemoveMeshesArray = [];
  50306. };
  50307. this._onMessageFromWorker = function (e) {
  50308. var returnData = e.data;
  50309. if (returnData.error != WorkerReplyType.SUCCESS) {
  50310. //TODO what errors can be returned from the worker?
  50311. BABYLON.Tools.Warn("error returned from worker!");
  50312. return;
  50313. }
  50314. switch (returnData.taskType) {
  50315. case WorkerTaskType.INIT:
  50316. _this._init = true;
  50317. //Update the worked with ALL of the scene's current state
  50318. _this._scene.meshes.forEach(function (mesh) {
  50319. _this.onMeshAdded(mesh);
  50320. });
  50321. _this._scene.getGeometries().forEach(function (geometry) {
  50322. _this.onGeometryAdded(geometry);
  50323. });
  50324. break;
  50325. case WorkerTaskType.UPDATE:
  50326. _this._runningUpdated--;
  50327. break;
  50328. case WorkerTaskType.COLLIDE:
  50329. var returnPayload = returnData.payload;
  50330. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50331. return;
  50332. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50333. if (callback) {
  50334. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50335. if (mesh) {
  50336. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50337. }
  50338. }
  50339. //cleanup
  50340. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50341. break;
  50342. }
  50343. };
  50344. this._collisionsCallbackArray = [];
  50345. this._init = false;
  50346. this._runningUpdated = 0;
  50347. this._addUpdateMeshesList = {};
  50348. this._addUpdateGeometriesList = {};
  50349. this._toRemoveGeometryArray = [];
  50350. this._toRemoveMeshesArray = [];
  50351. }
  50352. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50353. if (!this._init)
  50354. return;
  50355. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50356. return;
  50357. position.divideToRef(collider._radius, this._scaledPosition);
  50358. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50359. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50360. var payload = {
  50361. collider: {
  50362. position: this._scaledPosition.asArray(),
  50363. velocity: this._scaledVelocity.asArray(),
  50364. radius: collider._radius.asArray()
  50365. },
  50366. collisionId: collisionIndex,
  50367. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50368. maximumRetry: maximumRetry
  50369. };
  50370. var message = {
  50371. payload: payload,
  50372. taskType: WorkerTaskType.COLLIDE
  50373. };
  50374. this._worker.postMessage(message);
  50375. };
  50376. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50377. this._scene = scene;
  50378. this._scene.registerAfterRender(this._afterRender);
  50379. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50380. this._worker = new Worker(workerUrl);
  50381. this._worker.onmessage = this._onMessageFromWorker;
  50382. var message = {
  50383. payload: {},
  50384. taskType: WorkerTaskType.INIT
  50385. };
  50386. this._worker.postMessage(message);
  50387. };
  50388. CollisionCoordinatorWorker.prototype.destroy = function () {
  50389. this._scene.unregisterAfterRender(this._afterRender);
  50390. this._worker.terminate();
  50391. };
  50392. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50393. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50394. this.onMeshUpdated(mesh);
  50395. };
  50396. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50397. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50398. };
  50399. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50400. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50401. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50402. this.onGeometryUpdated(geometry);
  50403. };
  50404. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50405. this._toRemoveGeometryArray.push(geometry.id);
  50406. };
  50407. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50408. var submeshes = [];
  50409. if (mesh.subMeshes) {
  50410. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50411. var boundingInfo = sm.getBoundingInfo();
  50412. return {
  50413. position: idx,
  50414. verticesStart: sm.verticesStart,
  50415. verticesCount: sm.verticesCount,
  50416. indexStart: sm.indexStart,
  50417. indexCount: sm.indexCount,
  50418. hasMaterial: !!sm.getMaterial(),
  50419. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50420. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50421. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50422. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50423. };
  50424. });
  50425. }
  50426. var geometryId = null;
  50427. if (mesh instanceof BABYLON.Mesh) {
  50428. var geometry = mesh.geometry;
  50429. geometryId = geometry ? geometry.id : null;
  50430. }
  50431. else if (mesh instanceof BABYLON.InstancedMesh) {
  50432. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50433. geometryId = geometry ? geometry.id : null;
  50434. }
  50435. var boundingInfo = mesh.getBoundingInfo();
  50436. return {
  50437. uniqueId: mesh.uniqueId,
  50438. id: mesh.id,
  50439. name: mesh.name,
  50440. geometryId: geometryId,
  50441. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50442. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50443. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50444. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50445. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50446. subMeshes: submeshes,
  50447. checkCollisions: mesh.checkCollisions
  50448. };
  50449. };
  50450. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50451. return {
  50452. id: geometry.id,
  50453. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50454. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50455. indices: new Uint32Array(geometry.getIndices() || []),
  50456. };
  50457. };
  50458. return CollisionCoordinatorWorker;
  50459. }());
  50460. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50461. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50462. function CollisionCoordinatorLegacy() {
  50463. this._scaledPosition = BABYLON.Vector3.Zero();
  50464. this._scaledVelocity = BABYLON.Vector3.Zero();
  50465. this._finalPosition = BABYLON.Vector3.Zero();
  50466. }
  50467. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50468. position.divideToRef(collider._radius, this._scaledPosition);
  50469. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50470. collider.collidedMesh = null;
  50471. collider._retry = 0;
  50472. collider._initialVelocity = this._scaledVelocity;
  50473. collider._initialPosition = this._scaledPosition;
  50474. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50475. this._finalPosition.multiplyInPlace(collider._radius);
  50476. //run the callback
  50477. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50478. };
  50479. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50480. this._scene = scene;
  50481. };
  50482. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50483. //Legacy need no destruction method.
  50484. };
  50485. //No update in legacy mode
  50486. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50487. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50488. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50489. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50490. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50491. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50492. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50493. if (excludedMesh === void 0) { excludedMesh = null; }
  50494. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50495. if (collider._retry >= maximumRetry) {
  50496. finalPosition.copyFrom(position);
  50497. return;
  50498. }
  50499. // Check if this is a mesh else camera or -1
  50500. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50501. collider._initialize(position, velocity, closeDistance);
  50502. // Check all meshes
  50503. for (var index = 0; index < this._scene.meshes.length; index++) {
  50504. var mesh = this._scene.meshes[index];
  50505. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50506. mesh._checkCollision(collider);
  50507. }
  50508. }
  50509. if (!collider.collisionFound) {
  50510. position.addToRef(velocity, finalPosition);
  50511. return;
  50512. }
  50513. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50514. collider._getResponse(position, velocity);
  50515. }
  50516. if (velocity.length() <= closeDistance) {
  50517. finalPosition.copyFrom(position);
  50518. return;
  50519. }
  50520. collider._retry++;
  50521. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50522. };
  50523. return CollisionCoordinatorLegacy;
  50524. }());
  50525. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50526. })(BABYLON || (BABYLON = {}));
  50527. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50528. var BABYLON;
  50529. (function (BABYLON) {
  50530. /**
  50531. * A particle represents one of the element emitted by a particle system.
  50532. * This is mainly define by its coordinates, direction, velocity and age.
  50533. */
  50534. var Particle = /** @class */ (function () {
  50535. /**
  50536. * Creates a new instance of @see Particle
  50537. * @param particleSystem the particle system the particle belongs to
  50538. */
  50539. function Particle(particleSystem) {
  50540. this.particleSystem = particleSystem;
  50541. /**
  50542. * The world position of the particle in the scene.
  50543. */
  50544. this.position = BABYLON.Vector3.Zero();
  50545. /**
  50546. * The world direction of the particle in the scene.
  50547. */
  50548. this.direction = BABYLON.Vector3.Zero();
  50549. /**
  50550. * The color of the particle.
  50551. */
  50552. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50553. /**
  50554. * The color change of the particle per step.
  50555. */
  50556. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50557. /**
  50558. * Defines how long will the life of the particle be.
  50559. */
  50560. this.lifeTime = 1.0;
  50561. /**
  50562. * The current age of the particle.
  50563. */
  50564. this.age = 0;
  50565. /**
  50566. * The current size of the particle.
  50567. */
  50568. this.size = 0;
  50569. /**
  50570. * The current angle of the particle.
  50571. */
  50572. this.angle = 0;
  50573. /**
  50574. * Defines how fast is the angle changing.
  50575. */
  50576. this.angularSpeed = 0;
  50577. /**
  50578. * Defines the cell index used by the particle to be rendered from a sprite.
  50579. */
  50580. this.cellIndex = 0;
  50581. this._currentFrameCounter = 0;
  50582. if (!this.particleSystem.isAnimationSheetEnabled) {
  50583. return;
  50584. }
  50585. this.cellIndex = this.particleSystem.startSpriteCellID;
  50586. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50587. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50588. }
  50589. else {
  50590. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50591. }
  50592. }
  50593. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50594. // (ageOffset / scaledUpdateSpeed) / available cells
  50595. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50596. this._currentFrameCounter += scaledUpdateSpeed;
  50597. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50598. this._currentFrameCounter = 0;
  50599. this.cellIndex++;
  50600. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50601. this.cellIndex = this.particleSystem.endSpriteCellID;
  50602. }
  50603. }
  50604. };
  50605. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50606. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50607. this.cellIndex++;
  50608. this._currentFrameCounter = 0;
  50609. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50610. if (this.particleSystem.spriteCellLoop) {
  50611. this.cellIndex = this.particleSystem.startSpriteCellID;
  50612. }
  50613. else {
  50614. this.cellIndex = this.particleSystem.endSpriteCellID;
  50615. }
  50616. }
  50617. }
  50618. else {
  50619. this._currentFrameCounter++;
  50620. }
  50621. };
  50622. /**
  50623. * Copy the properties of particle to another one.
  50624. * @param other the particle to copy the information to.
  50625. */
  50626. Particle.prototype.copyTo = function (other) {
  50627. other.position.copyFrom(this.position);
  50628. other.direction.copyFrom(this.direction);
  50629. other.color.copyFrom(this.color);
  50630. other.colorStep.copyFrom(this.colorStep);
  50631. other.lifeTime = this.lifeTime;
  50632. other.age = this.age;
  50633. other.size = this.size;
  50634. other.angle = this.angle;
  50635. other.angularSpeed = this.angularSpeed;
  50636. other.particleSystem = this.particleSystem;
  50637. other.cellIndex = this.cellIndex;
  50638. };
  50639. return Particle;
  50640. }());
  50641. BABYLON.Particle = Particle;
  50642. })(BABYLON || (BABYLON = {}));
  50643. //# sourceMappingURL=babylon.particle.js.map
  50644. var BABYLON;
  50645. (function (BABYLON) {
  50646. /**
  50647. * This represents a particle system in Babylon.
  50648. * 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.
  50649. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50650. * @example https://doc.babylonjs.com/babylon101/particles
  50651. */
  50652. var ParticleSystem = /** @class */ (function () {
  50653. /**
  50654. * Instantiates a particle system.
  50655. * 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.
  50656. * @param name The name of the particle system
  50657. * @param capacity The max number of particles alive at the same time
  50658. * @param scene The scene the particle system belongs to
  50659. * @param customEffect a custom effect used to change the way particles are rendered by default
  50660. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50661. * @param epsilon Offset used to render the particles
  50662. */
  50663. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50664. if (customEffect === void 0) { customEffect = null; }
  50665. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50666. if (epsilon === void 0) { epsilon = 0.01; }
  50667. var _this = this;
  50668. /**
  50669. * List of animations used by the particle system.
  50670. */
  50671. this.animations = [];
  50672. /**
  50673. * The rendering group used by the Particle system to chose when to render.
  50674. */
  50675. this.renderingGroupId = 0;
  50676. /**
  50677. * The emitter represents the Mesh or position we are attaching the particle system to.
  50678. */
  50679. this.emitter = null;
  50680. /**
  50681. * The maximum number of particles to emit per frame
  50682. */
  50683. this.emitRate = 10;
  50684. /**
  50685. * If you want to launch only a few particles at once, that can be done, as well.
  50686. */
  50687. this.manualEmitCount = -1;
  50688. /**
  50689. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50690. */
  50691. this.updateSpeed = 0.01;
  50692. /**
  50693. * The amount of time the particle system is running (depends of the overall update speed).
  50694. */
  50695. this.targetStopDuration = 0;
  50696. /**
  50697. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50698. */
  50699. this.disposeOnStop = false;
  50700. /**
  50701. * Minimum power of emitting particles.
  50702. */
  50703. this.minEmitPower = 1;
  50704. /**
  50705. * Maximum power of emitting particles.
  50706. */
  50707. this.maxEmitPower = 1;
  50708. /**
  50709. * Minimum life time of emitting particles.
  50710. */
  50711. this.minLifeTime = 1;
  50712. /**
  50713. * Maximum life time of emitting particles.
  50714. */
  50715. this.maxLifeTime = 1;
  50716. /**
  50717. * Minimum Size of emitting particles.
  50718. */
  50719. this.minSize = 1;
  50720. /**
  50721. * Maximum Size of emitting particles.
  50722. */
  50723. this.maxSize = 1;
  50724. /**
  50725. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50726. */
  50727. this.minAngularSpeed = 0;
  50728. /**
  50729. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50730. */
  50731. this.maxAngularSpeed = 0;
  50732. /**
  50733. * The layer mask we are rendering the particles through.
  50734. */
  50735. this.layerMask = 0x0FFFFFFF;
  50736. /**
  50737. * This can help using your own shader to render the particle system.
  50738. * The according effect will be created
  50739. */
  50740. this.customShader = null;
  50741. /**
  50742. * By default particle system starts as soon as they are created. This prevents the
  50743. * automatic start to happen and let you decide when to start emitting particles.
  50744. */
  50745. this.preventAutoStart = false;
  50746. /**
  50747. * Callback triggered when the particle animation is ending.
  50748. */
  50749. this.onAnimationEnd = null;
  50750. /**
  50751. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50752. */
  50753. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50754. /**
  50755. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50756. * to override the particles.
  50757. */
  50758. this.forceDepthWrite = false;
  50759. /**
  50760. * You can use gravity if you want to give an orientation to your particles.
  50761. */
  50762. this.gravity = BABYLON.Vector3.Zero();
  50763. /**
  50764. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50765. */
  50766. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50767. /**
  50768. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50769. */
  50770. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50771. /**
  50772. * Color the particle will have at the end of its lifetime.
  50773. */
  50774. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50775. /**
  50776. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50777. */
  50778. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50779. /**
  50780. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50781. */
  50782. this.spriteCellLoop = true;
  50783. /**
  50784. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50785. */
  50786. this.spriteCellChangeSpeed = 0;
  50787. /**
  50788. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50789. */
  50790. this.startSpriteCellID = 0;
  50791. /**
  50792. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50793. */
  50794. this.endSpriteCellID = 0;
  50795. /**
  50796. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50797. */
  50798. this.spriteCellWidth = 0;
  50799. /**
  50800. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50801. */
  50802. this.spriteCellHeight = 0;
  50803. /**
  50804. * An event triggered when the system is disposed.
  50805. */
  50806. this.onDisposeObservable = new BABYLON.Observable();
  50807. this._particles = new Array();
  50808. this._stockParticles = new Array();
  50809. this._newPartsExcess = 0;
  50810. this._vertexBuffers = {};
  50811. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50812. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50813. this._scaledDirection = BABYLON.Vector3.Zero();
  50814. this._scaledGravity = BABYLON.Vector3.Zero();
  50815. this._currentRenderId = -1;
  50816. this._started = false;
  50817. this._stopped = false;
  50818. this._actualFrame = 0;
  50819. this._vertexBufferSize = 11;
  50820. this._appendParticleVertexes = null;
  50821. this.id = name;
  50822. this.name = name;
  50823. this._capacity = capacity;
  50824. this._epsilon = epsilon;
  50825. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50826. if (isAnimationSheetEnabled) {
  50827. this._vertexBufferSize = 12;
  50828. }
  50829. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50830. this._customEffect = customEffect;
  50831. scene.particleSystems.push(this);
  50832. this._createIndexBuffer();
  50833. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50834. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50835. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50836. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50837. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50838. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50839. if (this._isAnimationSheetEnabled) {
  50840. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50841. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50842. }
  50843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50844. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50845. this._vertexBuffers["options"] = options;
  50846. // Default emitter type
  50847. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50848. this.updateFunction = function (particles) {
  50849. for (var index = 0; index < particles.length; index++) {
  50850. var particle = particles[index];
  50851. particle.age += _this._scaledUpdateSpeed;
  50852. if (particle.age >= particle.lifeTime) {
  50853. _this.recycleParticle(particle);
  50854. index--;
  50855. continue;
  50856. }
  50857. else {
  50858. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50859. particle.color.addInPlace(_this._scaledColorStep);
  50860. if (particle.color.a < 0)
  50861. particle.color.a = 0;
  50862. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50863. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50864. particle.position.addInPlace(_this._scaledDirection);
  50865. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50866. particle.direction.addInPlace(_this._scaledGravity);
  50867. if (_this._isAnimationSheetEnabled) {
  50868. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50869. }
  50870. }
  50871. }
  50872. };
  50873. }
  50874. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50875. /**
  50876. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50877. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50878. */
  50879. get: function () {
  50880. if (this.particleEmitterType.direction1) {
  50881. return this.particleEmitterType.direction1;
  50882. }
  50883. return BABYLON.Vector3.Zero();
  50884. },
  50885. set: function (value) {
  50886. if (this.particleEmitterType.direction1) {
  50887. this.particleEmitterType.direction1 = value;
  50888. }
  50889. },
  50890. enumerable: true,
  50891. configurable: true
  50892. });
  50893. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50894. /**
  50895. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50896. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50897. */
  50898. get: function () {
  50899. if (this.particleEmitterType.direction2) {
  50900. return this.particleEmitterType.direction2;
  50901. }
  50902. return BABYLON.Vector3.Zero();
  50903. },
  50904. set: function (value) {
  50905. if (this.particleEmitterType.direction2) {
  50906. this.particleEmitterType.direction2 = value;
  50907. }
  50908. },
  50909. enumerable: true,
  50910. configurable: true
  50911. });
  50912. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50913. /**
  50914. * 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.
  50915. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50916. */
  50917. get: function () {
  50918. if (this.particleEmitterType.minEmitBox) {
  50919. return this.particleEmitterType.minEmitBox;
  50920. }
  50921. return BABYLON.Vector3.Zero();
  50922. },
  50923. set: function (value) {
  50924. if (this.particleEmitterType.minEmitBox) {
  50925. this.particleEmitterType.minEmitBox = value;
  50926. }
  50927. },
  50928. enumerable: true,
  50929. configurable: true
  50930. });
  50931. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50932. /**
  50933. * 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.
  50934. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50935. */
  50936. get: function () {
  50937. if (this.particleEmitterType.maxEmitBox) {
  50938. return this.particleEmitterType.maxEmitBox;
  50939. }
  50940. return BABYLON.Vector3.Zero();
  50941. },
  50942. set: function (value) {
  50943. if (this.particleEmitterType.maxEmitBox) {
  50944. this.particleEmitterType.maxEmitBox = value;
  50945. }
  50946. },
  50947. enumerable: true,
  50948. configurable: true
  50949. });
  50950. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50951. /**
  50952. * Sets a callback that will be triggered when the system is disposed.
  50953. */
  50954. set: function (callback) {
  50955. if (this._onDisposeObserver) {
  50956. this.onDisposeObservable.remove(this._onDisposeObserver);
  50957. }
  50958. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50959. },
  50960. enumerable: true,
  50961. configurable: true
  50962. });
  50963. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50964. /**
  50965. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50966. */
  50967. get: function () {
  50968. return this._isAnimationSheetEnabled;
  50969. },
  50970. enumerable: true,
  50971. configurable: true
  50972. });
  50973. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50974. /**
  50975. * Gets the current list of active particles
  50976. */
  50977. get: function () {
  50978. return this._particles;
  50979. },
  50980. enumerable: true,
  50981. configurable: true
  50982. });
  50983. /**
  50984. * Returns the string "ParticleSystem"
  50985. * @returns a string containing the class name
  50986. */
  50987. ParticleSystem.prototype.getClassName = function () {
  50988. return "ParticleSystem";
  50989. };
  50990. ParticleSystem.prototype._createIndexBuffer = function () {
  50991. var indices = [];
  50992. var index = 0;
  50993. for (var count = 0; count < this._capacity; count++) {
  50994. indices.push(index);
  50995. indices.push(index + 1);
  50996. indices.push(index + 2);
  50997. indices.push(index);
  50998. indices.push(index + 2);
  50999. indices.push(index + 3);
  51000. index += 4;
  51001. }
  51002. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51003. };
  51004. /**
  51005. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51006. * Its lifetime will start back at 0.
  51007. * @param particle The particle to recycle
  51008. */
  51009. ParticleSystem.prototype.recycleParticle = function (particle) {
  51010. var lastParticle = this._particles.pop();
  51011. if (lastParticle !== particle) {
  51012. lastParticle.copyTo(particle);
  51013. this._stockParticles.push(lastParticle);
  51014. }
  51015. };
  51016. /**
  51017. * Gets the maximum number of particles active at the same time.
  51018. * @returns The max number of active particles.
  51019. */
  51020. ParticleSystem.prototype.getCapacity = function () {
  51021. return this._capacity;
  51022. };
  51023. /**
  51024. * Gets Wether there are still active particles in the system.
  51025. * @returns True if it is alive, otherwise false.
  51026. */
  51027. ParticleSystem.prototype.isAlive = function () {
  51028. return this._alive;
  51029. };
  51030. /**
  51031. * Gets Wether the system has been started.
  51032. * @returns True if it has been started, otherwise false.
  51033. */
  51034. ParticleSystem.prototype.isStarted = function () {
  51035. return this._started;
  51036. };
  51037. /**
  51038. * Starts the particle system and begins to emit.
  51039. */
  51040. ParticleSystem.prototype.start = function () {
  51041. this._started = true;
  51042. this._stopped = false;
  51043. this._actualFrame = 0;
  51044. };
  51045. /**
  51046. * Stops the particle system.
  51047. */
  51048. ParticleSystem.prototype.stop = function () {
  51049. this._stopped = true;
  51050. };
  51051. /**
  51052. * Remove all active particles
  51053. */
  51054. ParticleSystem.prototype.reset = function () {
  51055. this._stockParticles = [];
  51056. this._particles = [];
  51057. };
  51058. /**
  51059. * @ignore (for internal use only)
  51060. */
  51061. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51062. var offset = index * this._vertexBufferSize;
  51063. this._vertexData[offset] = particle.position.x;
  51064. this._vertexData[offset + 1] = particle.position.y;
  51065. this._vertexData[offset + 2] = particle.position.z;
  51066. this._vertexData[offset + 3] = particle.color.r;
  51067. this._vertexData[offset + 4] = particle.color.g;
  51068. this._vertexData[offset + 5] = particle.color.b;
  51069. this._vertexData[offset + 6] = particle.color.a;
  51070. this._vertexData[offset + 7] = particle.angle;
  51071. this._vertexData[offset + 8] = particle.size;
  51072. this._vertexData[offset + 9] = offsetX;
  51073. this._vertexData[offset + 10] = offsetY;
  51074. };
  51075. /**
  51076. * @ignore (for internal use only)
  51077. */
  51078. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51079. if (offsetX === 0)
  51080. offsetX = this._epsilon;
  51081. else if (offsetX === 1)
  51082. offsetX = 1 - this._epsilon;
  51083. if (offsetY === 0)
  51084. offsetY = this._epsilon;
  51085. else if (offsetY === 1)
  51086. offsetY = 1 - this._epsilon;
  51087. var offset = index * this._vertexBufferSize;
  51088. this._vertexData[offset] = particle.position.x;
  51089. this._vertexData[offset + 1] = particle.position.y;
  51090. this._vertexData[offset + 2] = particle.position.z;
  51091. this._vertexData[offset + 3] = particle.color.r;
  51092. this._vertexData[offset + 4] = particle.color.g;
  51093. this._vertexData[offset + 5] = particle.color.b;
  51094. this._vertexData[offset + 6] = particle.color.a;
  51095. this._vertexData[offset + 7] = particle.angle;
  51096. this._vertexData[offset + 8] = particle.size;
  51097. this._vertexData[offset + 9] = offsetX;
  51098. this._vertexData[offset + 10] = offsetY;
  51099. this._vertexData[offset + 11] = particle.cellIndex;
  51100. };
  51101. ParticleSystem.prototype._update = function (newParticles) {
  51102. // Update current
  51103. this._alive = this._particles.length > 0;
  51104. this.updateFunction(this._particles);
  51105. // Add new ones
  51106. var worldMatrix;
  51107. if (this.emitter.position) {
  51108. var emitterMesh = this.emitter;
  51109. worldMatrix = emitterMesh.getWorldMatrix();
  51110. }
  51111. else {
  51112. var emitterPosition = this.emitter;
  51113. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51114. }
  51115. var particle;
  51116. for (var index = 0; index < newParticles; index++) {
  51117. if (this._particles.length === this._capacity) {
  51118. break;
  51119. }
  51120. if (this._stockParticles.length !== 0) {
  51121. particle = this._stockParticles.pop();
  51122. particle.age = 0;
  51123. particle.cellIndex = this.startSpriteCellID;
  51124. }
  51125. else {
  51126. particle = new BABYLON.Particle(this);
  51127. }
  51128. this._particles.push(particle);
  51129. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51130. if (this.startPositionFunction) {
  51131. this.startPositionFunction(worldMatrix, particle.position, particle);
  51132. }
  51133. else {
  51134. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51135. }
  51136. if (this.startDirectionFunction) {
  51137. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51138. }
  51139. else {
  51140. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51141. }
  51142. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51143. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51144. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51145. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51146. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51147. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51148. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51149. }
  51150. };
  51151. ParticleSystem.prototype._getEffect = function () {
  51152. if (this._customEffect) {
  51153. return this._customEffect;
  51154. }
  51155. ;
  51156. var defines = [];
  51157. if (this._scene.clipPlane) {
  51158. defines.push("#define CLIPPLANE");
  51159. }
  51160. if (this._isAnimationSheetEnabled) {
  51161. defines.push("#define ANIMATESHEET");
  51162. }
  51163. // Effect
  51164. var join = defines.join("\n");
  51165. if (this._cachedDefines !== join) {
  51166. this._cachedDefines = join;
  51167. var attributesNamesOrOptions;
  51168. var effectCreationOption;
  51169. if (this._isAnimationSheetEnabled) {
  51170. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51171. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51172. }
  51173. else {
  51174. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51175. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51176. }
  51177. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51178. }
  51179. return this._effect;
  51180. };
  51181. /**
  51182. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51183. */
  51184. ParticleSystem.prototype.animate = function () {
  51185. if (!this._started)
  51186. return;
  51187. var effect = this._getEffect();
  51188. // Check
  51189. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51190. return;
  51191. if (this._currentRenderId === this._scene.getRenderId()) {
  51192. return;
  51193. }
  51194. this._currentRenderId = this._scene.getRenderId();
  51195. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51196. // determine the number of particles we need to create
  51197. var newParticles;
  51198. if (this.manualEmitCount > -1) {
  51199. newParticles = this.manualEmitCount;
  51200. this._newPartsExcess = 0;
  51201. this.manualEmitCount = 0;
  51202. }
  51203. else {
  51204. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51205. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51206. }
  51207. if (this._newPartsExcess > 1.0) {
  51208. newParticles += this._newPartsExcess >> 0;
  51209. this._newPartsExcess -= this._newPartsExcess >> 0;
  51210. }
  51211. this._alive = false;
  51212. if (!this._stopped) {
  51213. this._actualFrame += this._scaledUpdateSpeed;
  51214. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51215. this.stop();
  51216. }
  51217. else {
  51218. newParticles = 0;
  51219. }
  51220. this._update(newParticles);
  51221. // Stopped?
  51222. if (this._stopped) {
  51223. if (!this._alive) {
  51224. this._started = false;
  51225. if (this.onAnimationEnd) {
  51226. this.onAnimationEnd();
  51227. }
  51228. if (this.disposeOnStop) {
  51229. this._scene._toBeDisposed.push(this);
  51230. }
  51231. }
  51232. }
  51233. // Animation sheet
  51234. if (this._isAnimationSheetEnabled) {
  51235. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51236. }
  51237. else {
  51238. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51239. }
  51240. // Update VBO
  51241. var offset = 0;
  51242. for (var index = 0; index < this._particles.length; index++) {
  51243. var particle = this._particles[index];
  51244. this._appendParticleVertexes(offset, particle);
  51245. offset += 4;
  51246. }
  51247. if (this._vertexBuffer) {
  51248. this._vertexBuffer.update(this._vertexData);
  51249. }
  51250. };
  51251. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51252. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51253. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51254. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51255. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51256. };
  51257. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51258. this._appendParticleVertex(offset++, particle, 0, 0);
  51259. this._appendParticleVertex(offset++, particle, 1, 0);
  51260. this._appendParticleVertex(offset++, particle, 1, 1);
  51261. this._appendParticleVertex(offset++, particle, 0, 1);
  51262. };
  51263. /**
  51264. * Rebuilds the particle system.
  51265. */
  51266. ParticleSystem.prototype.rebuild = function () {
  51267. this._createIndexBuffer();
  51268. if (this._vertexBuffer) {
  51269. this._vertexBuffer._rebuild();
  51270. }
  51271. };
  51272. /**
  51273. * Renders the particle system in its current state.
  51274. * @returns the current number of particles
  51275. */
  51276. ParticleSystem.prototype.render = function () {
  51277. var effect = this._getEffect();
  51278. // Check
  51279. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51280. return 0;
  51281. }
  51282. var engine = this._scene.getEngine();
  51283. // Render
  51284. engine.enableEffect(effect);
  51285. engine.setState(false);
  51286. var viewMatrix = this._scene.getViewMatrix();
  51287. effect.setTexture("diffuseSampler", this.particleTexture);
  51288. effect.setMatrix("view", viewMatrix);
  51289. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51290. if (this._isAnimationSheetEnabled) {
  51291. var baseSize = this.particleTexture.getBaseSize();
  51292. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51293. }
  51294. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51295. if (this._scene.clipPlane) {
  51296. var clipPlane = this._scene.clipPlane;
  51297. var invView = viewMatrix.clone();
  51298. invView.invert();
  51299. effect.setMatrix("invView", invView);
  51300. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51301. }
  51302. // VBOs
  51303. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51304. // Draw order
  51305. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51306. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51307. }
  51308. else {
  51309. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51310. }
  51311. if (this.forceDepthWrite) {
  51312. engine.setDepthWrite(true);
  51313. }
  51314. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51316. return this._particles.length;
  51317. };
  51318. /**
  51319. * Disposes the particle system and free the associated resources
  51320. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51321. */
  51322. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51323. if (disposeTexture === void 0) { disposeTexture = true; }
  51324. if (this._vertexBuffer) {
  51325. this._vertexBuffer.dispose();
  51326. this._vertexBuffer = null;
  51327. }
  51328. if (this._indexBuffer) {
  51329. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51330. this._indexBuffer = null;
  51331. }
  51332. if (disposeTexture && this.particleTexture) {
  51333. this.particleTexture.dispose();
  51334. this.particleTexture = null;
  51335. }
  51336. // Remove from scene
  51337. var index = this._scene.particleSystems.indexOf(this);
  51338. if (index > -1) {
  51339. this._scene.particleSystems.splice(index, 1);
  51340. }
  51341. // Callback
  51342. this.onDisposeObservable.notifyObservers(this);
  51343. this.onDisposeObservable.clear();
  51344. };
  51345. /**
  51346. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51347. * @param radius The radius of the sphere to emit from
  51348. * @returns the emitter
  51349. */
  51350. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51351. if (radius === void 0) { radius = 1; }
  51352. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51353. this.particleEmitterType = particleEmitter;
  51354. return particleEmitter;
  51355. };
  51356. /**
  51357. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51358. * @param radius The radius of the sphere to emit from
  51359. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51360. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51361. * @returns the emitter
  51362. */
  51363. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51364. if (radius === void 0) { radius = 1; }
  51365. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51366. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51367. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51368. this.particleEmitterType = particleEmitter;
  51369. return particleEmitter;
  51370. };
  51371. /**
  51372. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51373. * @param radius The radius of the cone to emit from
  51374. * @param angle The base angle of the cone
  51375. * @returns the emitter
  51376. */
  51377. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51378. if (radius === void 0) { radius = 1; }
  51379. if (angle === void 0) { angle = Math.PI / 4; }
  51380. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51381. this.particleEmitterType = particleEmitter;
  51382. return particleEmitter;
  51383. };
  51384. // 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.
  51385. /**
  51386. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51387. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51388. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51389. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51390. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51391. * @returns the emitter
  51392. */
  51393. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51394. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51395. this.direction1 = direction1;
  51396. this.direction2 = direction2;
  51397. this.minEmitBox = minEmitBox;
  51398. this.maxEmitBox = maxEmitBox;
  51399. this.particleEmitterType = particleEmitter;
  51400. return particleEmitter;
  51401. };
  51402. /**
  51403. * Clones the particle system.
  51404. * @param name The name of the cloned object
  51405. * @param newEmitter The new emitter to use
  51406. * @returns the cloned particle system
  51407. */
  51408. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51409. var custom = null;
  51410. var program = null;
  51411. if (this.customShader != null) {
  51412. program = this.customShader;
  51413. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51414. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51415. }
  51416. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51417. result.customShader = program;
  51418. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51419. if (newEmitter === undefined) {
  51420. newEmitter = this.emitter;
  51421. }
  51422. result.emitter = newEmitter;
  51423. if (this.particleTexture) {
  51424. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51425. }
  51426. if (!this.preventAutoStart) {
  51427. result.start();
  51428. }
  51429. return result;
  51430. };
  51431. /**
  51432. * Serializes the particle system to a JSON object.
  51433. * @returns the JSON object
  51434. */
  51435. ParticleSystem.prototype.serialize = function () {
  51436. var serializationObject = {};
  51437. serializationObject.name = this.name;
  51438. serializationObject.id = this.id;
  51439. // Emitter
  51440. if (this.emitter.position) {
  51441. var emitterMesh = this.emitter;
  51442. serializationObject.emitterId = emitterMesh.id;
  51443. }
  51444. else {
  51445. var emitterPosition = this.emitter;
  51446. serializationObject.emitter = emitterPosition.asArray();
  51447. }
  51448. serializationObject.capacity = this.getCapacity();
  51449. if (this.particleTexture) {
  51450. serializationObject.textureName = this.particleTexture.name;
  51451. }
  51452. // Animations
  51453. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51454. // Particle system
  51455. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51456. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51457. serializationObject.minSize = this.minSize;
  51458. serializationObject.maxSize = this.maxSize;
  51459. serializationObject.minEmitPower = this.minEmitPower;
  51460. serializationObject.maxEmitPower = this.maxEmitPower;
  51461. serializationObject.minLifeTime = this.minLifeTime;
  51462. serializationObject.maxLifeTime = this.maxLifeTime;
  51463. serializationObject.emitRate = this.emitRate;
  51464. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51465. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51466. serializationObject.gravity = this.gravity.asArray();
  51467. serializationObject.direction1 = this.direction1.asArray();
  51468. serializationObject.direction2 = this.direction2.asArray();
  51469. serializationObject.color1 = this.color1.asArray();
  51470. serializationObject.color2 = this.color2.asArray();
  51471. serializationObject.colorDead = this.colorDead.asArray();
  51472. serializationObject.updateSpeed = this.updateSpeed;
  51473. serializationObject.targetStopDuration = this.targetStopDuration;
  51474. serializationObject.textureMask = this.textureMask.asArray();
  51475. serializationObject.blendMode = this.blendMode;
  51476. serializationObject.customShader = this.customShader;
  51477. serializationObject.preventAutoStart = this.preventAutoStart;
  51478. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51479. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51480. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51481. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51482. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51483. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51484. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51485. // Emitter
  51486. if (this.particleEmitterType) {
  51487. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51488. }
  51489. return serializationObject;
  51490. };
  51491. /**
  51492. * Parses a JSON object to create a particle system.
  51493. * @param parsedParticleSystem The JSON object to parse
  51494. * @param scene The scene to create the particle system in
  51495. * @param rootUrl The root url to use to load external dependencies like texture
  51496. * @returns the Parsed particle system
  51497. */
  51498. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51499. var name = parsedParticleSystem.name;
  51500. var custom = null;
  51501. var program = null;
  51502. if (parsedParticleSystem.customShader) {
  51503. program = parsedParticleSystem.customShader;
  51504. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51505. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51506. }
  51507. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51508. particleSystem.customShader = program;
  51509. if (parsedParticleSystem.id) {
  51510. particleSystem.id = parsedParticleSystem.id;
  51511. }
  51512. // Auto start
  51513. if (parsedParticleSystem.preventAutoStart) {
  51514. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51515. }
  51516. // Texture
  51517. if (parsedParticleSystem.textureName) {
  51518. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51519. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51520. }
  51521. // Emitter
  51522. if (parsedParticleSystem.emitterId) {
  51523. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51524. }
  51525. else {
  51526. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51527. }
  51528. // Animations
  51529. if (parsedParticleSystem.animations) {
  51530. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51531. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51532. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51533. }
  51534. }
  51535. if (parsedParticleSystem.autoAnimate) {
  51536. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51537. }
  51538. // Particle system
  51539. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51540. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51541. particleSystem.minSize = parsedParticleSystem.minSize;
  51542. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51543. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51544. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51545. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51546. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51547. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51548. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51549. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51550. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51551. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51552. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51553. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51554. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51555. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51556. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51557. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51558. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51559. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51560. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51561. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51562. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51563. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51564. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51565. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51566. if (!particleSystem.preventAutoStart) {
  51567. particleSystem.start();
  51568. }
  51569. return particleSystem;
  51570. };
  51571. /**
  51572. * Source color is added to the destination color without alpha affecting the result.
  51573. */
  51574. ParticleSystem.BLENDMODE_ONEONE = 0;
  51575. /**
  51576. * Blend current color and particle color using particle’s alpha.
  51577. */
  51578. ParticleSystem.BLENDMODE_STANDARD = 1;
  51579. return ParticleSystem;
  51580. }());
  51581. BABYLON.ParticleSystem = ParticleSystem;
  51582. })(BABYLON || (BABYLON = {}));
  51583. //# sourceMappingURL=babylon.particleSystem.js.map
  51584. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51585. var BABYLON;
  51586. (function (BABYLON) {
  51587. /**
  51588. * Particle emitter emitting particles from the inside of a box.
  51589. * It emits the particles randomly between 2 given directions.
  51590. */
  51591. var BoxParticleEmitter = /** @class */ (function () {
  51592. /**
  51593. * Creates a new instance of @see BoxParticleEmitter
  51594. */
  51595. function BoxParticleEmitter() {
  51596. /**
  51597. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51598. */
  51599. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51600. /**
  51601. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51602. */
  51603. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51604. /**
  51605. * 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.
  51606. */
  51607. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51608. /**
  51609. * 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.
  51610. */
  51611. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51612. }
  51613. /**
  51614. * Called by the particle System when the direction is computed for the created particle.
  51615. * @param emitPower is the power of the particle (speed)
  51616. * @param worldMatrix is the world matrix of the particle system
  51617. * @param directionToUpdate is the direction vector to update with the result
  51618. * @param particle is the particle we are computed the direction for
  51619. */
  51620. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51621. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51622. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51623. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51624. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51625. };
  51626. /**
  51627. * Called by the particle System when the position is computed for the created particle.
  51628. * @param worldMatrix is the world matrix of the particle system
  51629. * @param positionToUpdate is the position vector to update with the result
  51630. * @param particle is the particle we are computed the position for
  51631. */
  51632. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51633. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51634. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51635. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51636. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51637. };
  51638. /**
  51639. * Clones the current emitter and returns a copy of it
  51640. * @returns the new emitter
  51641. */
  51642. BoxParticleEmitter.prototype.clone = function () {
  51643. var newOne = new BoxParticleEmitter();
  51644. BABYLON.Tools.DeepCopy(this, newOne);
  51645. return newOne;
  51646. };
  51647. /**
  51648. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51649. * @param effect defines the update shader
  51650. */
  51651. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51652. effect.setVector3("direction1", this.direction1);
  51653. effect.setVector3("direction2", this.direction2);
  51654. effect.setVector3("minEmitBox", this.minEmitBox);
  51655. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51656. };
  51657. /**
  51658. * Returns a string to use to update the GPU particles update shader
  51659. * @returns a string containng the defines string
  51660. */
  51661. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51662. return "#define BOXEMITTER";
  51663. };
  51664. /**
  51665. * Returns the string "BoxEmitter"
  51666. * @returns a string containing the class name
  51667. */
  51668. BoxParticleEmitter.prototype.getClassName = function () {
  51669. return "BoxEmitter";
  51670. };
  51671. /**
  51672. * Serializes the particle system to a JSON object.
  51673. * @returns the JSON object
  51674. */
  51675. BoxParticleEmitter.prototype.serialize = function () {
  51676. var serializationObject = {};
  51677. serializationObject.type = this.getClassName();
  51678. serializationObject.direction1 = this.direction1.asArray();
  51679. ;
  51680. serializationObject.direction2 = this.direction2.asArray();
  51681. ;
  51682. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51683. ;
  51684. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51685. ;
  51686. return serializationObject;
  51687. };
  51688. /**
  51689. * Parse properties from a JSON object
  51690. * @param serializationObject defines the JSON object
  51691. */
  51692. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51693. this.direction1.copyFrom(serializationObject.direction1);
  51694. this.direction2.copyFrom(serializationObject.direction2);
  51695. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51696. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51697. };
  51698. return BoxParticleEmitter;
  51699. }());
  51700. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51701. })(BABYLON || (BABYLON = {}));
  51702. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51703. var BABYLON;
  51704. (function (BABYLON) {
  51705. /**
  51706. * Particle emitter emitting particles from the inside of a cone.
  51707. * It emits the particles alongside the cone volume from the base to the particle.
  51708. * The emission direction might be randomized.
  51709. */
  51710. var ConeParticleEmitter = /** @class */ (function () {
  51711. /**
  51712. * Creates a new instance of @see ConeParticleEmitter
  51713. * @param radius the radius of the emission cone (1 by default)
  51714. * @param angles the cone base angle (PI by default)
  51715. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51716. */
  51717. function ConeParticleEmitter(radius,
  51718. /**
  51719. * The radius of the emission cone.
  51720. */
  51721. angle,
  51722. /**
  51723. * The cone base angle.
  51724. */
  51725. directionRandomizer) {
  51726. if (radius === void 0) { radius = 1; }
  51727. if (angle === void 0) { angle = Math.PI; }
  51728. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51729. this.angle = angle;
  51730. this.directionRandomizer = directionRandomizer;
  51731. this.radius = radius;
  51732. }
  51733. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51734. /**
  51735. * Gets the radius of the emission cone.
  51736. */
  51737. get: function () {
  51738. return this._radius;
  51739. },
  51740. /**
  51741. * Sets the radius of the emission cone.
  51742. */
  51743. set: function (value) {
  51744. this._radius = value;
  51745. if (this.angle !== 0) {
  51746. this._height = value / Math.tan(this.angle / 2);
  51747. }
  51748. else {
  51749. this._height = 1;
  51750. }
  51751. },
  51752. enumerable: true,
  51753. configurable: true
  51754. });
  51755. /**
  51756. * Called by the particle System when the direction is computed for the created particle.
  51757. * @param emitPower is the power of the particle (speed)
  51758. * @param worldMatrix is the world matrix of the particle system
  51759. * @param directionToUpdate is the direction vector to update with the result
  51760. * @param particle is the particle we are computed the direction for
  51761. */
  51762. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51763. if (this.angle === 0) {
  51764. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51765. }
  51766. else {
  51767. // measure the direction Vector from the emitter to the particle.
  51768. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51769. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51770. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51771. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51772. direction.x += randX;
  51773. direction.y += randY;
  51774. direction.z += randZ;
  51775. direction.normalize();
  51776. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51777. }
  51778. };
  51779. /**
  51780. * Called by the particle System when the position is computed for the created particle.
  51781. * @param worldMatrix is the world matrix of the particle system
  51782. * @param positionToUpdate is the position vector to update with the result
  51783. * @param particle is the particle we are computed the position for
  51784. */
  51785. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51786. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51787. var h = BABYLON.Scalar.RandomRange(0, 1);
  51788. // Better distribution in a cone at normal angles.
  51789. h = 1 - h * h;
  51790. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51791. radius = radius * h / this._height;
  51792. var randX = radius * Math.sin(s);
  51793. var randZ = radius * Math.cos(s);
  51794. var randY = h * this._height;
  51795. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51796. };
  51797. /**
  51798. * Clones the current emitter and returns a copy of it
  51799. * @returns the new emitter
  51800. */
  51801. ConeParticleEmitter.prototype.clone = function () {
  51802. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51803. BABYLON.Tools.DeepCopy(this, newOne);
  51804. return newOne;
  51805. };
  51806. /**
  51807. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51808. * @param effect defines the update shader
  51809. */
  51810. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51811. effect.setFloat("radius", this.radius);
  51812. effect.setFloat("angle", this.angle);
  51813. effect.setFloat("height", this._height);
  51814. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51815. };
  51816. /**
  51817. * Returns a string to use to update the GPU particles update shader
  51818. * @returns a string containng the defines string
  51819. */
  51820. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51821. return "#define CONEEMITTER";
  51822. };
  51823. /**
  51824. * Returns the string "BoxEmitter"
  51825. * @returns a string containing the class name
  51826. */
  51827. ConeParticleEmitter.prototype.getClassName = function () {
  51828. return "ConeEmitter";
  51829. };
  51830. /**
  51831. * Serializes the particle system to a JSON object.
  51832. * @returns the JSON object
  51833. */
  51834. ConeParticleEmitter.prototype.serialize = function () {
  51835. var serializationObject = {};
  51836. serializationObject.type = this.getClassName();
  51837. serializationObject.radius = this.radius;
  51838. serializationObject.angle = this.angle;
  51839. serializationObject.directionRandomizer = this.directionRandomizer;
  51840. return serializationObject;
  51841. };
  51842. /**
  51843. * Parse properties from a JSON object
  51844. * @param serializationObject defines the JSON object
  51845. */
  51846. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51847. this.radius = serializationObject.radius;
  51848. this.angle = serializationObject.angle;
  51849. this.directionRandomizer = serializationObject.directionRandomizer;
  51850. };
  51851. return ConeParticleEmitter;
  51852. }());
  51853. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51854. })(BABYLON || (BABYLON = {}));
  51855. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51856. var BABYLON;
  51857. (function (BABYLON) {
  51858. /**
  51859. * Particle emitter emitting particles from the inside of a sphere.
  51860. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51861. */
  51862. var SphereParticleEmitter = /** @class */ (function () {
  51863. /**
  51864. * Creates a new instance of @see SphereParticleEmitter
  51865. * @param radius the radius of the emission sphere (1 by default)
  51866. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51867. */
  51868. function SphereParticleEmitter(
  51869. /**
  51870. * The radius of the emission sphere.
  51871. */
  51872. radius,
  51873. /**
  51874. * How much to randomize the particle direction [0-1].
  51875. */
  51876. directionRandomizer) {
  51877. if (radius === void 0) { radius = 1; }
  51878. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51879. this.radius = radius;
  51880. this.directionRandomizer = directionRandomizer;
  51881. }
  51882. /**
  51883. * Called by the particle System when the direction is computed for the created particle.
  51884. * @param emitPower is the power of the particle (speed)
  51885. * @param worldMatrix is the world matrix of the particle system
  51886. * @param directionToUpdate is the direction vector to update with the result
  51887. * @param particle is the particle we are computed the direction for
  51888. */
  51889. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51890. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51891. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51892. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51893. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51894. direction.x += randX;
  51895. direction.y += randY;
  51896. direction.z += randZ;
  51897. direction.normalize();
  51898. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51899. };
  51900. /**
  51901. * Called by the particle System when the position is computed for the created particle.
  51902. * @param worldMatrix is the world matrix of the particle system
  51903. * @param positionToUpdate is the position vector to update with the result
  51904. * @param particle is the particle we are computed the position for
  51905. */
  51906. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51907. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51908. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51909. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51910. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51911. var randY = randRadius * Math.cos(theta);
  51912. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51913. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51914. };
  51915. /**
  51916. * Clones the current emitter and returns a copy of it
  51917. * @returns the new emitter
  51918. */
  51919. SphereParticleEmitter.prototype.clone = function () {
  51920. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51921. BABYLON.Tools.DeepCopy(this, newOne);
  51922. return newOne;
  51923. };
  51924. /**
  51925. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51926. * @param effect defines the update shader
  51927. */
  51928. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51929. effect.setFloat("radius", this.radius);
  51930. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51931. };
  51932. /**
  51933. * Returns a string to use to update the GPU particles update shader
  51934. * @returns a string containng the defines string
  51935. */
  51936. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51937. return "#define SPHEREEMITTER";
  51938. };
  51939. /**
  51940. * Returns the string "SphereParticleEmitter"
  51941. * @returns a string containing the class name
  51942. */
  51943. SphereParticleEmitter.prototype.getClassName = function () {
  51944. return "SphereParticleEmitter";
  51945. };
  51946. /**
  51947. * Serializes the particle system to a JSON object.
  51948. * @returns the JSON object
  51949. */
  51950. SphereParticleEmitter.prototype.serialize = function () {
  51951. var serializationObject = {};
  51952. serializationObject.type = this.getClassName();
  51953. serializationObject.radius = this.radius;
  51954. serializationObject.directionRandomizer = this.directionRandomizer;
  51955. return serializationObject;
  51956. };
  51957. /**
  51958. * Parse properties from a JSON object
  51959. * @param serializationObject defines the JSON object
  51960. */
  51961. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51962. this.radius = serializationObject.radius;
  51963. this.directionRandomizer = serializationObject.directionRandomizer;
  51964. };
  51965. return SphereParticleEmitter;
  51966. }());
  51967. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51968. /**
  51969. * Particle emitter emitting particles from the inside of a sphere.
  51970. * It emits the particles randomly between two vectors.
  51971. */
  51972. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51973. __extends(SphereDirectedParticleEmitter, _super);
  51974. /**
  51975. * Creates a new instance of @see SphereDirectedParticleEmitter
  51976. * @param radius the radius of the emission sphere (1 by default)
  51977. * @param direction1 the min limit of the emission direction (up vector by default)
  51978. * @param direction2 the max limit of the emission direction (up vector by default)
  51979. */
  51980. function SphereDirectedParticleEmitter(radius,
  51981. /**
  51982. * The min limit of the emission direction.
  51983. */
  51984. direction1,
  51985. /**
  51986. * The max limit of the emission direction.
  51987. */
  51988. direction2) {
  51989. if (radius === void 0) { radius = 1; }
  51990. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51991. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51992. var _this = _super.call(this, radius) || this;
  51993. _this.direction1 = direction1;
  51994. _this.direction2 = direction2;
  51995. return _this;
  51996. }
  51997. /**
  51998. * Called by the particle System when the direction is computed for the created particle.
  51999. * @param emitPower is the power of the particle (speed)
  52000. * @param worldMatrix is the world matrix of the particle system
  52001. * @param directionToUpdate is the direction vector to update with the result
  52002. * @param particle is the particle we are computed the direction for
  52003. */
  52004. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52005. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52006. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52007. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52008. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52009. };
  52010. /**
  52011. * Clones the current emitter and returns a copy of it
  52012. * @returns the new emitter
  52013. */
  52014. SphereDirectedParticleEmitter.prototype.clone = function () {
  52015. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52016. BABYLON.Tools.DeepCopy(this, newOne);
  52017. return newOne;
  52018. };
  52019. /**
  52020. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52021. * @param effect defines the update shader
  52022. */
  52023. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52024. effect.setFloat("radius", this.radius);
  52025. effect.setVector3("direction1", this.direction1);
  52026. effect.setVector3("direction2", this.direction2);
  52027. };
  52028. /**
  52029. * Returns a string to use to update the GPU particles update shader
  52030. * @returns a string containng the defines string
  52031. */
  52032. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52033. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52034. };
  52035. /**
  52036. * Returns the string "SphereDirectedParticleEmitter"
  52037. * @returns a string containing the class name
  52038. */
  52039. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52040. return "SphereDirectedParticleEmitter";
  52041. };
  52042. /**
  52043. * Serializes the particle system to a JSON object.
  52044. * @returns the JSON object
  52045. */
  52046. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52047. var serializationObject = _super.prototype.serialize.call(this);
  52048. ;
  52049. serializationObject.direction1 = this.direction1.asArray();
  52050. ;
  52051. serializationObject.direction2 = this.direction2.asArray();
  52052. ;
  52053. return serializationObject;
  52054. };
  52055. /**
  52056. * Parse properties from a JSON object
  52057. * @param serializationObject defines the JSON object
  52058. */
  52059. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52060. _super.prototype.parse.call(this, serializationObject);
  52061. this.direction1.copyFrom(serializationObject.direction1);
  52062. this.direction2.copyFrom(serializationObject.direction2);
  52063. };
  52064. return SphereDirectedParticleEmitter;
  52065. }(SphereParticleEmitter));
  52066. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52067. })(BABYLON || (BABYLON = {}));
  52068. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52069. var BABYLON;
  52070. (function (BABYLON) {
  52071. /**
  52072. * Represents one particle of a solid particle system.
  52073. * @see SolidParticleSystem
  52074. */
  52075. var SolidParticle = /** @class */ (function () {
  52076. /**
  52077. * Creates a Solid Particle object.
  52078. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52079. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52080. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52081. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52082. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52083. * @param shapeId (integer) is the model shape identifier in the SPS.
  52084. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52085. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52086. */
  52087. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52088. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52089. /**
  52090. * particle global index
  52091. */
  52092. this.idx = 0;
  52093. /**
  52094. * The color of the particle
  52095. */
  52096. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52097. /**
  52098. * The world space position of the particle.
  52099. */
  52100. this.position = BABYLON.Vector3.Zero();
  52101. /**
  52102. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52103. */
  52104. this.rotation = BABYLON.Vector3.Zero();
  52105. /**
  52106. * The scaling of the particle.
  52107. */
  52108. this.scaling = BABYLON.Vector3.One();
  52109. /**
  52110. * The uvs of the particle.
  52111. */
  52112. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52113. /**
  52114. * The current speed of the particle.
  52115. */
  52116. this.velocity = BABYLON.Vector3.Zero();
  52117. /**
  52118. * The pivot point in the particle local space.
  52119. */
  52120. this.pivot = BABYLON.Vector3.Zero();
  52121. /**
  52122. * Must the particle be translated from its pivot point in its local space ?
  52123. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52124. * Default : false
  52125. */
  52126. this.translateFromPivot = false;
  52127. /**
  52128. * Is the particle active or not ?
  52129. */
  52130. this.alive = true;
  52131. /**
  52132. * Is the particle visible or not ?
  52133. */
  52134. this.isVisible = true;
  52135. /**
  52136. * Index of this particle in the global "positions" array (Internal use)
  52137. */
  52138. this._pos = 0;
  52139. /**
  52140. * Index of this particle in the global "indices" array (Internal use)
  52141. */
  52142. this._ind = 0;
  52143. /**
  52144. * ModelShape id of this particle
  52145. */
  52146. this.shapeId = 0;
  52147. /**
  52148. * Index of the particle in its shape id (Internal use)
  52149. */
  52150. this.idxInShape = 0;
  52151. /**
  52152. * Still set as invisible in order to skip useless computations (Internal use)
  52153. */
  52154. this._stillInvisible = false;
  52155. /**
  52156. * Last computed particle rotation matrix
  52157. */
  52158. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52159. /**
  52160. * Parent particle Id, if any.
  52161. * Default null.
  52162. */
  52163. this.parentId = null;
  52164. /**
  52165. * Internal global position in the SPS.
  52166. */
  52167. this._globalPosition = BABYLON.Vector3.Zero();
  52168. this.idx = particleIndex;
  52169. this._pos = positionIndex;
  52170. this._ind = indiceIndex;
  52171. this._model = model;
  52172. this.shapeId = shapeId;
  52173. this.idxInShape = idxInShape;
  52174. this._sps = sps;
  52175. if (modelBoundingInfo) {
  52176. this._modelBoundingInfo = modelBoundingInfo;
  52177. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52178. }
  52179. }
  52180. Object.defineProperty(SolidParticle.prototype, "scale", {
  52181. /**
  52182. * Legacy support, changed scale to scaling
  52183. */
  52184. get: function () {
  52185. return this.scaling;
  52186. },
  52187. /**
  52188. * Legacy support, changed scale to scaling
  52189. */
  52190. set: function (scale) {
  52191. this.scaling = scale;
  52192. },
  52193. enumerable: true,
  52194. configurable: true
  52195. });
  52196. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52197. /**
  52198. * Legacy support, changed quaternion to rotationQuaternion
  52199. */
  52200. get: function () {
  52201. return this.rotationQuaternion;
  52202. },
  52203. /**
  52204. * Legacy support, changed quaternion to rotationQuaternion
  52205. */
  52206. set: function (q) {
  52207. this.rotationQuaternion = q;
  52208. },
  52209. enumerable: true,
  52210. configurable: true
  52211. });
  52212. /**
  52213. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52214. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52215. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52216. * @returns true if it intersects
  52217. */
  52218. SolidParticle.prototype.intersectsMesh = function (target) {
  52219. if (!this._boundingInfo || !target._boundingInfo) {
  52220. return false;
  52221. }
  52222. if (this._sps._bSphereOnly) {
  52223. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52224. }
  52225. return this._boundingInfo.intersects(target._boundingInfo, false);
  52226. };
  52227. return SolidParticle;
  52228. }());
  52229. BABYLON.SolidParticle = SolidParticle;
  52230. /**
  52231. * Represents the shape of the model used by one particle of a solid particle system.
  52232. * SPS internal tool, don't use it manually.
  52233. * @see SolidParticleSystem
  52234. */
  52235. var ModelShape = /** @class */ (function () {
  52236. /**
  52237. * 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.
  52238. * SPS internal tool, don't use it manually.
  52239. * @ignore
  52240. */
  52241. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52242. /**
  52243. * length of the shape in the model indices array (internal use)
  52244. */
  52245. this._indicesLength = 0;
  52246. this.shapeID = id;
  52247. this._shape = shape;
  52248. this._indicesLength = indicesLength;
  52249. this._shapeUV = shapeUV;
  52250. this._positionFunction = posFunction;
  52251. this._vertexFunction = vtxFunction;
  52252. }
  52253. return ModelShape;
  52254. }());
  52255. BABYLON.ModelShape = ModelShape;
  52256. /**
  52257. * Represents a Depth Sorted Particle in the solid particle system.
  52258. * @see SolidParticleSystem
  52259. */
  52260. var DepthSortedParticle = /** @class */ (function () {
  52261. function DepthSortedParticle() {
  52262. /**
  52263. * Index of the particle in the "indices" array
  52264. */
  52265. this.ind = 0;
  52266. /**
  52267. * Length of the particle shape in the "indices" array
  52268. */
  52269. this.indicesLength = 0;
  52270. /**
  52271. * Squared distance from the particle to the camera
  52272. */
  52273. this.sqDistance = 0.0;
  52274. }
  52275. return DepthSortedParticle;
  52276. }());
  52277. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52278. })(BABYLON || (BABYLON = {}));
  52279. //# sourceMappingURL=babylon.solidParticle.js.map
  52280. var BABYLON;
  52281. (function (BABYLON) {
  52282. /**
  52283. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52284. *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.
  52285. * The SPS is also a particle system. It provides some methods to manage the particles.
  52286. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52287. *
  52288. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52289. */
  52290. var SolidParticleSystem = /** @class */ (function () {
  52291. /**
  52292. * Creates a SPS (Solid Particle System) object.
  52293. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52294. * @param scene (Scene) is the scene in which the SPS is added.
  52295. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52296. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52297. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52298. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52299. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52300. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52301. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52302. */
  52303. function SolidParticleSystem(name, scene, options) {
  52304. /**
  52305. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52306. * Example : var p = SPS.particles[i];
  52307. */
  52308. this.particles = new Array();
  52309. /**
  52310. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52311. */
  52312. this.nbParticles = 0;
  52313. /**
  52314. * If the particles must ever face the camera (default false). Useful for planar particles.
  52315. */
  52316. this.billboard = false;
  52317. /**
  52318. * Recompute normals when adding a shape
  52319. */
  52320. this.recomputeNormals = true;
  52321. /**
  52322. * This a counter ofr your own usage. It's not set by any SPS functions.
  52323. */
  52324. this.counter = 0;
  52325. /**
  52326. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52327. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52328. */
  52329. this.vars = {};
  52330. /**
  52331. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52332. */
  52333. this._bSphereOnly = false;
  52334. /**
  52335. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52336. */
  52337. this._bSphereRadiusFactor = 1.0;
  52338. this._positions = new Array();
  52339. this._indices = new Array();
  52340. this._normals = new Array();
  52341. this._colors = new Array();
  52342. this._uvs = new Array();
  52343. this._index = 0; // indices index
  52344. this._updatable = true;
  52345. this._pickable = false;
  52346. this._isVisibilityBoxLocked = false;
  52347. this._alwaysVisible = false;
  52348. this._depthSort = false;
  52349. this._shapeCounter = 0;
  52350. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52351. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52352. this._computeParticleColor = true;
  52353. this._computeParticleTexture = true;
  52354. this._computeParticleRotation = true;
  52355. this._computeParticleVertex = false;
  52356. this._computeBoundingBox = false;
  52357. this._depthSortParticles = true;
  52358. this._cam_axisZ = BABYLON.Vector3.Zero();
  52359. this._cam_axisY = BABYLON.Vector3.Zero();
  52360. this._cam_axisX = BABYLON.Vector3.Zero();
  52361. this._axisZ = BABYLON.Axis.Z;
  52362. this._camDir = BABYLON.Vector3.Zero();
  52363. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52364. this._rotMatrix = new BABYLON.Matrix();
  52365. this._invertMatrix = new BABYLON.Matrix();
  52366. this._rotated = BABYLON.Vector3.Zero();
  52367. this._quaternion = new BABYLON.Quaternion();
  52368. this._vertex = BABYLON.Vector3.Zero();
  52369. this._normal = BABYLON.Vector3.Zero();
  52370. this._yaw = 0.0;
  52371. this._pitch = 0.0;
  52372. this._roll = 0.0;
  52373. this._halfroll = 0.0;
  52374. this._halfpitch = 0.0;
  52375. this._halfyaw = 0.0;
  52376. this._sinRoll = 0.0;
  52377. this._cosRoll = 0.0;
  52378. this._sinPitch = 0.0;
  52379. this._cosPitch = 0.0;
  52380. this._sinYaw = 0.0;
  52381. this._cosYaw = 0.0;
  52382. this._mustUnrotateFixedNormals = false;
  52383. this._minimum = BABYLON.Vector3.Zero();
  52384. this._maximum = BABYLON.Vector3.Zero();
  52385. this._minBbox = BABYLON.Vector3.Zero();
  52386. this._maxBbox = BABYLON.Vector3.Zero();
  52387. this._particlesIntersect = false;
  52388. this._depthSortFunction = function (p1, p2) {
  52389. return (p2.sqDistance - p1.sqDistance);
  52390. };
  52391. this._needs32Bits = false;
  52392. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52393. this._scaledPivot = BABYLON.Vector3.Zero();
  52394. this._particleHasParent = false;
  52395. this.name = name;
  52396. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52397. this._camera = scene.activeCamera;
  52398. this._pickable = options ? options.isPickable : false;
  52399. this._depthSort = options ? options.enableDepthSort : false;
  52400. this._particlesIntersect = options ? options.particleIntersection : false;
  52401. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52402. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52403. if (options && options.updatable) {
  52404. this._updatable = options.updatable;
  52405. }
  52406. else {
  52407. this._updatable = true;
  52408. }
  52409. if (this._pickable) {
  52410. this.pickedParticles = [];
  52411. }
  52412. if (this._depthSort) {
  52413. this.depthSortedParticles = [];
  52414. }
  52415. }
  52416. /**
  52417. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52418. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52419. * @returns the created mesh
  52420. */
  52421. SolidParticleSystem.prototype.buildMesh = function () {
  52422. if (this.nbParticles === 0) {
  52423. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52424. this.addShape(triangle, 1);
  52425. triangle.dispose();
  52426. }
  52427. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52428. this._positions32 = new Float32Array(this._positions);
  52429. this._uvs32 = new Float32Array(this._uvs);
  52430. this._colors32 = new Float32Array(this._colors);
  52431. if (this.recomputeNormals) {
  52432. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52433. }
  52434. this._normals32 = new Float32Array(this._normals);
  52435. this._fixedNormal32 = new Float32Array(this._normals);
  52436. if (this._mustUnrotateFixedNormals) {
  52437. this._unrotateFixedNormals();
  52438. }
  52439. var vertexData = new BABYLON.VertexData();
  52440. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52441. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52442. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52443. if (this._uvs32) {
  52444. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52445. ;
  52446. }
  52447. if (this._colors32) {
  52448. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52449. }
  52450. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52451. vertexData.applyToMesh(mesh, this._updatable);
  52452. this.mesh = mesh;
  52453. this.mesh.isPickable = this._pickable;
  52454. // free memory
  52455. if (!this._depthSort) {
  52456. this._indices = null;
  52457. }
  52458. this._positions = null;
  52459. this._normals = null;
  52460. this._uvs = null;
  52461. this._colors = null;
  52462. if (!this._updatable) {
  52463. this.particles.length = 0;
  52464. }
  52465. return mesh;
  52466. };
  52467. /**
  52468. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52469. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52470. * Thus the particles generated from `digest()` have their property `position` set yet.
  52471. * @param mesh ( Mesh ) is the mesh to be digested
  52472. * @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
  52473. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52474. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52475. * @returns the current SPS
  52476. */
  52477. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52478. var size = (options && options.facetNb) || 1;
  52479. var number = (options && options.number) || 0;
  52480. var delta = (options && options.delta) || 0;
  52481. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52482. var meshInd = mesh.getIndices();
  52483. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52484. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52485. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52486. var f = 0; // facet counter
  52487. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52488. // compute size from number
  52489. if (number) {
  52490. number = (number > totalFacets) ? totalFacets : number;
  52491. size = Math.round(totalFacets / number);
  52492. delta = 0;
  52493. }
  52494. else {
  52495. size = (size > totalFacets) ? totalFacets : size;
  52496. }
  52497. var facetPos = []; // submesh positions
  52498. var facetInd = []; // submesh indices
  52499. var facetUV = []; // submesh UV
  52500. var facetCol = []; // submesh colors
  52501. var barycenter = BABYLON.Vector3.Zero();
  52502. var sizeO = size;
  52503. while (f < totalFacets) {
  52504. size = sizeO + Math.floor((1 + delta) * Math.random());
  52505. if (f > totalFacets - size) {
  52506. size = totalFacets - f;
  52507. }
  52508. // reset temp arrays
  52509. facetPos.length = 0;
  52510. facetInd.length = 0;
  52511. facetUV.length = 0;
  52512. facetCol.length = 0;
  52513. // iterate over "size" facets
  52514. var fi = 0;
  52515. for (var j = f * 3; j < (f + size) * 3; j++) {
  52516. facetInd.push(fi);
  52517. var i = meshInd[j];
  52518. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52519. if (meshUV) {
  52520. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52521. }
  52522. if (meshCol) {
  52523. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52524. }
  52525. fi++;
  52526. }
  52527. // create a model shape for each single particle
  52528. var idx = this.nbParticles;
  52529. var shape = this._posToShape(facetPos);
  52530. var shapeUV = this._uvsToShapeUV(facetUV);
  52531. // compute the barycenter of the shape
  52532. var v;
  52533. for (v = 0; v < shape.length; v++) {
  52534. barycenter.addInPlace(shape[v]);
  52535. }
  52536. barycenter.scaleInPlace(1 / shape.length);
  52537. // shift the shape from its barycenter to the origin
  52538. for (v = 0; v < shape.length; v++) {
  52539. shape[v].subtractInPlace(barycenter);
  52540. }
  52541. var bInfo;
  52542. if (this._particlesIntersect) {
  52543. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52544. }
  52545. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52546. // add the particle in the SPS
  52547. var currentPos = this._positions.length;
  52548. var currentInd = this._indices.length;
  52549. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52550. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52551. // initialize the particle position
  52552. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52553. this._index += shape.length;
  52554. idx++;
  52555. this.nbParticles++;
  52556. this._shapeCounter++;
  52557. f += size;
  52558. }
  52559. return this;
  52560. };
  52561. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52562. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52563. var index = 0;
  52564. var idx = 0;
  52565. for (var p = 0; p < this.particles.length; p++) {
  52566. this._particle = this.particles[p];
  52567. this._shape = this._particle._model._shape;
  52568. if (this._particle.rotationQuaternion) {
  52569. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52570. }
  52571. else {
  52572. this._yaw = this._particle.rotation.y;
  52573. this._pitch = this._particle.rotation.x;
  52574. this._roll = this._particle.rotation.z;
  52575. this._quaternionRotationYPR();
  52576. }
  52577. this._quaternionToRotationMatrix();
  52578. this._rotMatrix.invertToRef(this._invertMatrix);
  52579. for (var pt = 0; pt < this._shape.length; pt++) {
  52580. idx = index + pt * 3;
  52581. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52582. this._fixedNormal32[idx] = this._normal.x;
  52583. this._fixedNormal32[idx + 1] = this._normal.y;
  52584. this._fixedNormal32[idx + 2] = this._normal.z;
  52585. }
  52586. index = idx + 3;
  52587. }
  52588. };
  52589. //reset copy
  52590. SolidParticleSystem.prototype._resetCopy = function () {
  52591. this._copy.position.x = 0;
  52592. this._copy.position.y = 0;
  52593. this._copy.position.z = 0;
  52594. this._copy.rotation.x = 0;
  52595. this._copy.rotation.y = 0;
  52596. this._copy.rotation.z = 0;
  52597. this._copy.rotationQuaternion = null;
  52598. this._copy.scaling.x = 1.0;
  52599. this._copy.scaling.y = 1.0;
  52600. this._copy.scaling.z = 1.0;
  52601. this._copy.uvs.x = 0;
  52602. this._copy.uvs.y = 0;
  52603. this._copy.uvs.z = 1.0;
  52604. this._copy.uvs.w = 1.0;
  52605. this._copy.color = null;
  52606. this._copy.translateFromPivot = false;
  52607. };
  52608. // _meshBuilder : inserts the shape model in the global SPS mesh
  52609. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52610. var i;
  52611. var u = 0;
  52612. var c = 0;
  52613. var n = 0;
  52614. this._resetCopy();
  52615. if (options && options.positionFunction) {
  52616. options.positionFunction(this._copy, idx, idxInShape);
  52617. this._mustUnrotateFixedNormals = true;
  52618. }
  52619. if (this._copy.rotationQuaternion) {
  52620. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52621. }
  52622. else {
  52623. this._yaw = this._copy.rotation.y;
  52624. this._pitch = this._copy.rotation.x;
  52625. this._roll = this._copy.rotation.z;
  52626. this._quaternionRotationYPR();
  52627. }
  52628. this._quaternionToRotationMatrix();
  52629. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52630. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52631. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52632. if (this._copy.translateFromPivot) {
  52633. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52634. }
  52635. else {
  52636. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52637. }
  52638. for (i = 0; i < shape.length; i++) {
  52639. this._vertex.x = shape[i].x;
  52640. this._vertex.y = shape[i].y;
  52641. this._vertex.z = shape[i].z;
  52642. if (options && options.vertexFunction) {
  52643. options.vertexFunction(this._copy, this._vertex, i);
  52644. }
  52645. this._vertex.x *= this._copy.scaling.x;
  52646. this._vertex.y *= this._copy.scaling.y;
  52647. this._vertex.z *= this._copy.scaling.z;
  52648. this._vertex.x -= this._scaledPivot.x;
  52649. this._vertex.y -= this._scaledPivot.y;
  52650. this._vertex.z -= this._scaledPivot.z;
  52651. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52652. this._rotated.addInPlace(this._pivotBackTranslation);
  52653. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52654. if (meshUV) {
  52655. 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);
  52656. u += 2;
  52657. }
  52658. if (this._copy.color) {
  52659. this._color = this._copy.color;
  52660. }
  52661. else if (meshCol && meshCol[c] !== undefined) {
  52662. this._color.r = meshCol[c];
  52663. this._color.g = meshCol[c + 1];
  52664. this._color.b = meshCol[c + 2];
  52665. this._color.a = meshCol[c + 3];
  52666. }
  52667. else {
  52668. this._color.r = 1.0;
  52669. this._color.g = 1.0;
  52670. this._color.b = 1.0;
  52671. this._color.a = 1.0;
  52672. }
  52673. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52674. c += 4;
  52675. if (!this.recomputeNormals && meshNor) {
  52676. this._normal.x = meshNor[n];
  52677. this._normal.y = meshNor[n + 1];
  52678. this._normal.z = meshNor[n + 2];
  52679. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52680. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52681. n += 3;
  52682. }
  52683. }
  52684. for (i = 0; i < meshInd.length; i++) {
  52685. var current_ind = p + meshInd[i];
  52686. indices.push(current_ind);
  52687. if (current_ind > 65535) {
  52688. this._needs32Bits = true;
  52689. }
  52690. }
  52691. if (this._pickable) {
  52692. var nbfaces = meshInd.length / 3;
  52693. for (i = 0; i < nbfaces; i++) {
  52694. this.pickedParticles.push({ idx: idx, faceId: i });
  52695. }
  52696. }
  52697. if (this._depthSort) {
  52698. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52699. }
  52700. return this._copy;
  52701. };
  52702. // returns a shape array from positions array
  52703. SolidParticleSystem.prototype._posToShape = function (positions) {
  52704. var shape = [];
  52705. for (var i = 0; i < positions.length; i += 3) {
  52706. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52707. }
  52708. return shape;
  52709. };
  52710. // returns a shapeUV array from a Vector4 uvs
  52711. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52712. var shapeUV = [];
  52713. if (uvs) {
  52714. for (var i = 0; i < uvs.length; i++)
  52715. shapeUV.push(uvs[i]);
  52716. }
  52717. return shapeUV;
  52718. };
  52719. // adds a new particle object in the particles array
  52720. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52721. if (bInfo === void 0) { bInfo = null; }
  52722. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52723. this.particles.push(sp);
  52724. return sp;
  52725. };
  52726. /**
  52727. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52728. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52729. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52730. * @param nb (positive integer) the number of particles to be created from this model
  52731. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52732. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52733. * @returns the number of shapes in the system
  52734. */
  52735. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52736. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52737. var meshInd = mesh.getIndices();
  52738. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52739. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52740. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52741. var bbInfo;
  52742. if (this._particlesIntersect) {
  52743. bbInfo = mesh.getBoundingInfo();
  52744. }
  52745. var shape = this._posToShape(meshPos);
  52746. var shapeUV = this._uvsToShapeUV(meshUV);
  52747. var posfunc = options ? options.positionFunction : null;
  52748. var vtxfunc = options ? options.vertexFunction : null;
  52749. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52750. // particles
  52751. var sp;
  52752. var currentCopy;
  52753. var idx = this.nbParticles;
  52754. for (var i = 0; i < nb; i++) {
  52755. var currentPos = this._positions.length;
  52756. var currentInd = this._indices.length;
  52757. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52758. if (this._updatable) {
  52759. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52760. sp.position.copyFrom(currentCopy.position);
  52761. sp.rotation.copyFrom(currentCopy.rotation);
  52762. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52763. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52764. }
  52765. if (currentCopy.color && sp.color) {
  52766. sp.color.copyFrom(currentCopy.color);
  52767. }
  52768. sp.scaling.copyFrom(currentCopy.scaling);
  52769. sp.uvs.copyFrom(currentCopy.uvs);
  52770. }
  52771. this._index += shape.length;
  52772. idx++;
  52773. }
  52774. this.nbParticles += nb;
  52775. this._shapeCounter++;
  52776. return this._shapeCounter - 1;
  52777. };
  52778. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52779. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52780. this._resetCopy();
  52781. if (particle._model._positionFunction) {
  52782. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52783. }
  52784. if (this._copy.rotationQuaternion) {
  52785. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52786. }
  52787. else {
  52788. this._yaw = this._copy.rotation.y;
  52789. this._pitch = this._copy.rotation.x;
  52790. this._roll = this._copy.rotation.z;
  52791. this._quaternionRotationYPR();
  52792. }
  52793. this._quaternionToRotationMatrix();
  52794. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52795. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52796. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52797. if (this._copy.translateFromPivot) {
  52798. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52799. }
  52800. else {
  52801. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52802. }
  52803. this._shape = particle._model._shape;
  52804. for (var pt = 0; pt < this._shape.length; pt++) {
  52805. this._vertex.x = this._shape[pt].x;
  52806. this._vertex.y = this._shape[pt].y;
  52807. this._vertex.z = this._shape[pt].z;
  52808. if (particle._model._vertexFunction) {
  52809. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52810. }
  52811. this._vertex.x *= this._copy.scaling.x;
  52812. this._vertex.y *= this._copy.scaling.y;
  52813. this._vertex.z *= this._copy.scaling.z;
  52814. this._vertex.x -= this._scaledPivot.x;
  52815. this._vertex.y -= this._scaledPivot.y;
  52816. this._vertex.z -= this._scaledPivot.z;
  52817. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52818. this._rotated.addInPlace(this._pivotBackTranslation);
  52819. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52820. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52821. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52822. }
  52823. particle.position.x = 0.0;
  52824. particle.position.y = 0.0;
  52825. particle.position.z = 0.0;
  52826. particle.rotation.x = 0.0;
  52827. particle.rotation.y = 0.0;
  52828. particle.rotation.z = 0.0;
  52829. particle.rotationQuaternion = null;
  52830. particle.scaling.x = 1.0;
  52831. particle.scaling.y = 1.0;
  52832. particle.scaling.z = 1.0;
  52833. particle.uvs.x = 0.0;
  52834. particle.uvs.y = 0.0;
  52835. particle.uvs.z = 1.0;
  52836. particle.uvs.w = 1.0;
  52837. particle.pivot.x = 0.0;
  52838. particle.pivot.y = 0.0;
  52839. particle.pivot.z = 0.0;
  52840. particle.translateFromPivot = false;
  52841. particle.parentId = null;
  52842. };
  52843. /**
  52844. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52845. * @returns the SPS.
  52846. */
  52847. SolidParticleSystem.prototype.rebuildMesh = function () {
  52848. for (var p = 0; p < this.particles.length; p++) {
  52849. this._rebuildParticle(this.particles[p]);
  52850. }
  52851. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52852. return this;
  52853. };
  52854. /**
  52855. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52856. * This method calls `updateParticle()` for each particle of the SPS.
  52857. * For an animated SPS, it is usually called within the render loop.
  52858. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52859. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52860. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52861. * @returns the SPS.
  52862. */
  52863. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52864. if (start === void 0) { start = 0; }
  52865. if (end === void 0) { end = this.nbParticles - 1; }
  52866. if (update === void 0) { update = true; }
  52867. if (!this._updatable) {
  52868. return this;
  52869. }
  52870. // custom beforeUpdate
  52871. this.beforeUpdateParticles(start, end, update);
  52872. this._cam_axisX.x = 1.0;
  52873. this._cam_axisX.y = 0.0;
  52874. this._cam_axisX.z = 0.0;
  52875. this._cam_axisY.x = 0.0;
  52876. this._cam_axisY.y = 1.0;
  52877. this._cam_axisY.z = 0.0;
  52878. this._cam_axisZ.x = 0.0;
  52879. this._cam_axisZ.y = 0.0;
  52880. this._cam_axisZ.z = 1.0;
  52881. // cases when the World Matrix is to be computed first
  52882. if (this.billboard || this._depthSort) {
  52883. this.mesh.computeWorldMatrix(true);
  52884. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52885. }
  52886. // if the particles will always face the camera
  52887. if (this.billboard) {
  52888. // compute the camera position and un-rotate it by the current mesh rotation
  52889. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52890. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52891. this._cam_axisZ.normalize();
  52892. // same for camera up vector extracted from the cam view matrix
  52893. var view = this._camera.getViewMatrix(true);
  52894. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52895. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52896. this._cam_axisY.normalize();
  52897. this._cam_axisX.normalize();
  52898. }
  52899. // if depthSort, compute the camera global position in the mesh local system
  52900. if (this._depthSort) {
  52901. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52902. }
  52903. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52904. var idx = 0; // current position index in the global array positions32
  52905. var index = 0; // position start index in the global array positions32 of the current particle
  52906. var colidx = 0; // current color index in the global array colors32
  52907. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52908. var uvidx = 0; // current uv index in the global array uvs32
  52909. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52910. var pt = 0; // current index in the particle model shape
  52911. if (this.mesh.isFacetDataEnabled) {
  52912. this._computeBoundingBox = true;
  52913. }
  52914. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52915. if (this._computeBoundingBox) {
  52916. if (start == 0 && end == this.nbParticles - 1) {
  52917. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52918. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52919. }
  52920. else {
  52921. if (this.mesh._boundingInfo) {
  52922. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52923. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52924. }
  52925. }
  52926. }
  52927. // particle loop
  52928. index = this.particles[start]._pos;
  52929. var vpos = (index / 3) | 0;
  52930. colorIndex = vpos * 4;
  52931. uvIndex = vpos * 2;
  52932. for (var p = start; p <= end; p++) {
  52933. this._particle = this.particles[p];
  52934. this._shape = this._particle._model._shape;
  52935. this._shapeUV = this._particle._model._shapeUV;
  52936. // call to custom user function to update the particle properties
  52937. this.updateParticle(this._particle);
  52938. // camera-particle distance for depth sorting
  52939. if (this._depthSort && this._depthSortParticles) {
  52940. var dsp = this.depthSortedParticles[p];
  52941. dsp.ind = this._particle._ind;
  52942. dsp.indicesLength = this._particle._model._indicesLength;
  52943. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52944. }
  52945. // skip the computations for inactive or already invisible particles
  52946. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52947. // increment indexes for the next particle
  52948. pt = this._shape.length;
  52949. index += pt * 3;
  52950. colorIndex += pt * 4;
  52951. uvIndex += pt * 2;
  52952. continue;
  52953. }
  52954. if (this._particle.isVisible) {
  52955. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52956. this._particleHasParent = (this._particle.parentId !== null);
  52957. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52958. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52959. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52960. // particle rotation matrix
  52961. if (this.billboard) {
  52962. this._particle.rotation.x = 0.0;
  52963. this._particle.rotation.y = 0.0;
  52964. }
  52965. if (this._computeParticleRotation || this.billboard) {
  52966. if (this._particle.rotationQuaternion) {
  52967. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52968. }
  52969. else {
  52970. this._yaw = this._particle.rotation.y;
  52971. this._pitch = this._particle.rotation.x;
  52972. this._roll = this._particle.rotation.z;
  52973. this._quaternionRotationYPR();
  52974. }
  52975. this._quaternionToRotationMatrix();
  52976. }
  52977. if (this._particleHasParent) {
  52978. this._parent = this.particles[this._particle.parentId];
  52979. 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];
  52980. 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];
  52981. 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];
  52982. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52983. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52984. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52985. if (this._computeParticleRotation || this.billboard) {
  52986. 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];
  52987. 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];
  52988. 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];
  52989. 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];
  52990. 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];
  52991. 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];
  52992. 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];
  52993. 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];
  52994. 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];
  52995. }
  52996. }
  52997. else {
  52998. this._particle._globalPosition.x = this._particle.position.x;
  52999. this._particle._globalPosition.y = this._particle.position.y;
  53000. this._particle._globalPosition.z = this._particle.position.z;
  53001. if (this._computeParticleRotation || this.billboard) {
  53002. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53003. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53004. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53005. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53006. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53007. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53008. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53009. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53010. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53011. }
  53012. }
  53013. if (this._particle.translateFromPivot) {
  53014. this._pivotBackTranslation.x = 0.0;
  53015. this._pivotBackTranslation.y = 0.0;
  53016. this._pivotBackTranslation.z = 0.0;
  53017. }
  53018. else {
  53019. this._pivotBackTranslation.x = this._scaledPivot.x;
  53020. this._pivotBackTranslation.y = this._scaledPivot.y;
  53021. this._pivotBackTranslation.z = this._scaledPivot.z;
  53022. }
  53023. // particle vertex loop
  53024. for (pt = 0; pt < this._shape.length; pt++) {
  53025. idx = index + pt * 3;
  53026. colidx = colorIndex + pt * 4;
  53027. uvidx = uvIndex + pt * 2;
  53028. this._vertex.x = this._shape[pt].x;
  53029. this._vertex.y = this._shape[pt].y;
  53030. this._vertex.z = this._shape[pt].z;
  53031. if (this._computeParticleVertex) {
  53032. this.updateParticleVertex(this._particle, this._vertex, pt);
  53033. }
  53034. // positions
  53035. this._vertex.x *= this._particle.scaling.x;
  53036. this._vertex.y *= this._particle.scaling.y;
  53037. this._vertex.z *= this._particle.scaling.z;
  53038. this._vertex.x -= this._scaledPivot.x;
  53039. this._vertex.y -= this._scaledPivot.y;
  53040. this._vertex.z -= this._scaledPivot.z;
  53041. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53042. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53043. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53044. this._rotated.x += this._pivotBackTranslation.x;
  53045. this._rotated.y += this._pivotBackTranslation.y;
  53046. this._rotated.z += this._pivotBackTranslation.z;
  53047. 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;
  53048. 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;
  53049. 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;
  53050. if (this._computeBoundingBox) {
  53051. if (this._positions32[idx] < this._minimum.x) {
  53052. this._minimum.x = this._positions32[idx];
  53053. }
  53054. if (this._positions32[idx] > this._maximum.x) {
  53055. this._maximum.x = this._positions32[idx];
  53056. }
  53057. if (this._positions32[idx + 1] < this._minimum.y) {
  53058. this._minimum.y = this._positions32[idx + 1];
  53059. }
  53060. if (this._positions32[idx + 1] > this._maximum.y) {
  53061. this._maximum.y = this._positions32[idx + 1];
  53062. }
  53063. if (this._positions32[idx + 2] < this._minimum.z) {
  53064. this._minimum.z = this._positions32[idx + 2];
  53065. }
  53066. if (this._positions32[idx + 2] > this._maximum.z) {
  53067. this._maximum.z = this._positions32[idx + 2];
  53068. }
  53069. }
  53070. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53071. if (!this._computeParticleVertex) {
  53072. this._normal.x = this._fixedNormal32[idx];
  53073. this._normal.y = this._fixedNormal32[idx + 1];
  53074. this._normal.z = this._fixedNormal32[idx + 2];
  53075. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53076. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53077. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53078. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53079. 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;
  53080. 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;
  53081. }
  53082. if (this._computeParticleColor && this._particle.color) {
  53083. this._colors32[colidx] = this._particle.color.r;
  53084. this._colors32[colidx + 1] = this._particle.color.g;
  53085. this._colors32[colidx + 2] = this._particle.color.b;
  53086. this._colors32[colidx + 3] = this._particle.color.a;
  53087. }
  53088. if (this._computeParticleTexture) {
  53089. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53090. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53091. }
  53092. }
  53093. }
  53094. else {
  53095. this._particle._stillInvisible = true; // mark the particle as invisible
  53096. for (pt = 0; pt < this._shape.length; pt++) {
  53097. idx = index + pt * 3;
  53098. colidx = colorIndex + pt * 4;
  53099. uvidx = uvIndex + pt * 2;
  53100. this._positions32[idx] = 0.0;
  53101. this._positions32[idx + 1] = 0.0;
  53102. this._positions32[idx + 2] = 0.0;
  53103. this._normals32[idx] = 0.0;
  53104. this._normals32[idx + 1] = 0.0;
  53105. this._normals32[idx + 2] = 0.0;
  53106. if (this._computeParticleColor && this._particle.color) {
  53107. this._colors32[colidx] = this._particle.color.r;
  53108. this._colors32[colidx + 1] = this._particle.color.g;
  53109. this._colors32[colidx + 2] = this._particle.color.b;
  53110. this._colors32[colidx + 3] = this._particle.color.a;
  53111. }
  53112. if (this._computeParticleTexture) {
  53113. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53114. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53115. }
  53116. }
  53117. }
  53118. // if the particle intersections must be computed : update the bbInfo
  53119. if (this._particlesIntersect) {
  53120. var bInfo = this._particle._boundingInfo;
  53121. var bBox = bInfo.boundingBox;
  53122. var bSphere = bInfo.boundingSphere;
  53123. if (!this._bSphereOnly) {
  53124. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53125. for (var b = 0; b < bBox.vectors.length; b++) {
  53126. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53127. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53128. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53129. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53130. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53131. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53132. 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;
  53133. 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;
  53134. 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;
  53135. }
  53136. bBox._update(this.mesh._worldMatrix);
  53137. }
  53138. // place and scale the particle bouding sphere in the SPS local system, then update it
  53139. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53140. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53141. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53142. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53143. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53144. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53145. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53146. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53147. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53148. 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));
  53149. bSphere._update(this.mesh._worldMatrix);
  53150. }
  53151. // increment indexes for the next particle
  53152. index = idx + 3;
  53153. colorIndex = colidx + 4;
  53154. uvIndex = uvidx + 2;
  53155. }
  53156. // if the VBO must be updated
  53157. if (update) {
  53158. if (this._computeParticleColor) {
  53159. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53160. }
  53161. if (this._computeParticleTexture) {
  53162. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53163. }
  53164. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53165. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53166. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53167. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53168. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53169. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53170. for (var i = 0; i < this._normals32.length; i++) {
  53171. this._fixedNormal32[i] = this._normals32[i];
  53172. }
  53173. }
  53174. if (!this.mesh.areNormalsFrozen) {
  53175. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53176. }
  53177. }
  53178. if (this._depthSort && this._depthSortParticles) {
  53179. this.depthSortedParticles.sort(this._depthSortFunction);
  53180. var dspl = this.depthSortedParticles.length;
  53181. var sorted = 0;
  53182. var lind = 0;
  53183. var sind = 0;
  53184. var sid = 0;
  53185. for (sorted = 0; sorted < dspl; sorted++) {
  53186. lind = this.depthSortedParticles[sorted].indicesLength;
  53187. sind = this.depthSortedParticles[sorted].ind;
  53188. for (var i = 0; i < lind; i++) {
  53189. this._indices32[sid] = this._indices[sind + i];
  53190. sid++;
  53191. }
  53192. }
  53193. this.mesh.updateIndices(this._indices32);
  53194. }
  53195. }
  53196. if (this._computeBoundingBox) {
  53197. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53198. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53199. }
  53200. this.afterUpdateParticles(start, end, update);
  53201. return this;
  53202. };
  53203. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53204. this._halfroll = this._roll * 0.5;
  53205. this._halfpitch = this._pitch * 0.5;
  53206. this._halfyaw = this._yaw * 0.5;
  53207. this._sinRoll = Math.sin(this._halfroll);
  53208. this._cosRoll = Math.cos(this._halfroll);
  53209. this._sinPitch = Math.sin(this._halfpitch);
  53210. this._cosPitch = Math.cos(this._halfpitch);
  53211. this._sinYaw = Math.sin(this._halfyaw);
  53212. this._cosYaw = Math.cos(this._halfyaw);
  53213. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53214. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53215. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53216. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53217. };
  53218. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53219. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53220. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53221. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53222. this._rotMatrix.m[3] = 0;
  53223. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53224. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53225. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53226. this._rotMatrix.m[7] = 0;
  53227. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53228. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53229. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53230. this._rotMatrix.m[11] = 0;
  53231. this._rotMatrix.m[12] = 0;
  53232. this._rotMatrix.m[13] = 0;
  53233. this._rotMatrix.m[14] = 0;
  53234. this._rotMatrix.m[15] = 1.0;
  53235. };
  53236. /**
  53237. * Disposes the SPS.
  53238. */
  53239. SolidParticleSystem.prototype.dispose = function () {
  53240. this.mesh.dispose();
  53241. this.vars = null;
  53242. // drop references to internal big arrays for the GC
  53243. this._positions = null;
  53244. this._indices = null;
  53245. this._normals = null;
  53246. this._uvs = null;
  53247. this._colors = null;
  53248. this._indices32 = null;
  53249. this._positions32 = null;
  53250. this._normals32 = null;
  53251. this._fixedNormal32 = null;
  53252. this._uvs32 = null;
  53253. this._colors32 = null;
  53254. this.pickedParticles = null;
  53255. };
  53256. /**
  53257. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53258. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53259. * @returns the SPS.
  53260. */
  53261. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53262. if (!this._isVisibilityBoxLocked) {
  53263. this.mesh.refreshBoundingInfo();
  53264. }
  53265. return this;
  53266. };
  53267. /**
  53268. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53269. * @param size the size (float) of the visibility box
  53270. * note : this doesn't lock the SPS mesh bounding box.
  53271. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53272. */
  53273. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53274. var vis = size / 2;
  53275. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53276. };
  53277. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53278. /**
  53279. * Gets whether the SPS as always visible or not
  53280. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53281. */
  53282. get: function () {
  53283. return this._alwaysVisible;
  53284. },
  53285. /**
  53286. * Sets the SPS as always visible or not
  53287. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53288. */
  53289. set: function (val) {
  53290. this._alwaysVisible = val;
  53291. this.mesh.alwaysSelectAsActiveMesh = val;
  53292. },
  53293. enumerable: true,
  53294. configurable: true
  53295. });
  53296. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53297. /**
  53298. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53299. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53300. */
  53301. get: function () {
  53302. return this._isVisibilityBoxLocked;
  53303. },
  53304. /**
  53305. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53306. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53307. */
  53308. set: function (val) {
  53309. this._isVisibilityBoxLocked = val;
  53310. var boundingInfo = this.mesh.getBoundingInfo();
  53311. boundingInfo.isLocked = val;
  53312. },
  53313. enumerable: true,
  53314. configurable: true
  53315. });
  53316. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53317. /**
  53318. * Gets if `setParticles()` computes the particle rotations or not.
  53319. * Default value : true. The SPS is faster when it's set to false.
  53320. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53321. */
  53322. get: function () {
  53323. return this._computeParticleRotation;
  53324. },
  53325. /**
  53326. * Tells to `setParticles()` to compute the particle rotations or not.
  53327. * Default value : true. The SPS is faster when it's set to false.
  53328. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53329. */
  53330. set: function (val) {
  53331. this._computeParticleRotation = val;
  53332. },
  53333. enumerable: true,
  53334. configurable: true
  53335. });
  53336. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53337. /**
  53338. * Gets if `setParticles()` computes the particle colors or not.
  53339. * Default value : true. The SPS is faster when it's set to false.
  53340. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53341. */
  53342. get: function () {
  53343. return this._computeParticleColor;
  53344. },
  53345. /**
  53346. * Tells to `setParticles()` to compute the particle colors or not.
  53347. * Default value : true. The SPS is faster when it's set to false.
  53348. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53349. */
  53350. set: function (val) {
  53351. this._computeParticleColor = val;
  53352. },
  53353. enumerable: true,
  53354. configurable: true
  53355. });
  53356. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53357. /**
  53358. * Gets if `setParticles()` computes the particle textures or not.
  53359. * Default value : true. The SPS is faster when it's set to false.
  53360. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53361. */
  53362. get: function () {
  53363. return this._computeParticleTexture;
  53364. },
  53365. set: function (val) {
  53366. this._computeParticleTexture = val;
  53367. },
  53368. enumerable: true,
  53369. configurable: true
  53370. });
  53371. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53372. /**
  53373. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53374. * Default value : false. The SPS is faster when it's set to false.
  53375. * Note : the particle custom vertex positions aren't stored values.
  53376. */
  53377. get: function () {
  53378. return this._computeParticleVertex;
  53379. },
  53380. /**
  53381. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53382. * Default value : false. The SPS is faster when it's set to false.
  53383. * Note : the particle custom vertex positions aren't stored values.
  53384. */
  53385. set: function (val) {
  53386. this._computeParticleVertex = val;
  53387. },
  53388. enumerable: true,
  53389. configurable: true
  53390. });
  53391. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53392. /**
  53393. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53394. */
  53395. get: function () {
  53396. return this._computeBoundingBox;
  53397. },
  53398. /**
  53399. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53400. */
  53401. set: function (val) {
  53402. this._computeBoundingBox = val;
  53403. },
  53404. enumerable: true,
  53405. configurable: true
  53406. });
  53407. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53408. /**
  53409. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53410. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53411. * Default : `true`
  53412. */
  53413. get: function () {
  53414. return this._depthSortParticles;
  53415. },
  53416. /**
  53417. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53418. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53419. * Default : `true`
  53420. */
  53421. set: function (val) {
  53422. this._depthSortParticles = val;
  53423. },
  53424. enumerable: true,
  53425. configurable: true
  53426. });
  53427. // =======================================================================
  53428. // Particle behavior logic
  53429. // these following methods may be overwritten by the user to fit his needs
  53430. /**
  53431. * This function does nothing. It may be overwritten to set all the particle first values.
  53432. * The SPS doesn't call this function, you may have to call it by your own.
  53433. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53434. */
  53435. SolidParticleSystem.prototype.initParticles = function () {
  53436. };
  53437. /**
  53438. * This function does nothing. It may be overwritten to recycle a particle.
  53439. * The SPS doesn't call this function, you may have to call it by your own.
  53440. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53441. * @param particle The particle to recycle
  53442. * @returns the recycled particle
  53443. */
  53444. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53445. return particle;
  53446. };
  53447. /**
  53448. * Updates a particle : this function should be overwritten by the user.
  53449. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53450. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53451. * @example : just set a particle position or velocity and recycle conditions
  53452. * @param particle The particle to update
  53453. * @returns the updated particle
  53454. */
  53455. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53456. return particle;
  53457. };
  53458. /**
  53459. * Updates a vertex of a particle : it can be overwritten by the user.
  53460. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53461. * @param particle the current particle
  53462. * @param vertex the current index of the current particle
  53463. * @param pt the index of the current vertex in the particle shape
  53464. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53465. * @example : just set a vertex particle position
  53466. * @returns the updated vertex
  53467. */
  53468. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53469. return vertex;
  53470. };
  53471. /**
  53472. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53473. * This does nothing and may be overwritten by the user.
  53474. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53475. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53476. * @param update the boolean update value actually passed to setParticles()
  53477. */
  53478. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53479. };
  53480. /**
  53481. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53482. * This will be passed three parameters.
  53483. * This does nothing and may be overwritten by the user.
  53484. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53485. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53486. * @param update the boolean update value actually passed to setParticles()
  53487. */
  53488. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53489. };
  53490. return SolidParticleSystem;
  53491. }());
  53492. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53493. })(BABYLON || (BABYLON = {}));
  53494. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53495. var BABYLON;
  53496. (function (BABYLON) {
  53497. var ShaderMaterial = /** @class */ (function (_super) {
  53498. __extends(ShaderMaterial, _super);
  53499. function ShaderMaterial(name, scene, shaderPath, options) {
  53500. var _this = _super.call(this, name, scene) || this;
  53501. _this._textures = {};
  53502. _this._textureArrays = {};
  53503. _this._floats = {};
  53504. _this._ints = {};
  53505. _this._floatsArrays = {};
  53506. _this._colors3 = {};
  53507. _this._colors3Arrays = {};
  53508. _this._colors4 = {};
  53509. _this._vectors2 = {};
  53510. _this._vectors3 = {};
  53511. _this._vectors4 = {};
  53512. _this._matrices = {};
  53513. _this._matrices3x3 = {};
  53514. _this._matrices2x2 = {};
  53515. _this._vectors2Arrays = {};
  53516. _this._vectors3Arrays = {};
  53517. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53518. _this._shaderPath = shaderPath;
  53519. options.needAlphaBlending = options.needAlphaBlending || false;
  53520. options.needAlphaTesting = options.needAlphaTesting || false;
  53521. options.attributes = options.attributes || ["position", "normal", "uv"];
  53522. options.uniforms = options.uniforms || ["worldViewProjection"];
  53523. options.uniformBuffers = options.uniformBuffers || [];
  53524. options.samplers = options.samplers || [];
  53525. options.defines = options.defines || [];
  53526. _this._options = options;
  53527. return _this;
  53528. }
  53529. ShaderMaterial.prototype.getClassName = function () {
  53530. return "ShaderMaterial";
  53531. };
  53532. ShaderMaterial.prototype.needAlphaBlending = function () {
  53533. return this._options.needAlphaBlending;
  53534. };
  53535. ShaderMaterial.prototype.needAlphaTesting = function () {
  53536. return this._options.needAlphaTesting;
  53537. };
  53538. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53539. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53540. this._options.uniforms.push(uniformName);
  53541. }
  53542. };
  53543. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53544. if (this._options.samplers.indexOf(name) === -1) {
  53545. this._options.samplers.push(name);
  53546. }
  53547. this._textures[name] = texture;
  53548. return this;
  53549. };
  53550. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53551. if (this._options.samplers.indexOf(name) === -1) {
  53552. this._options.samplers.push(name);
  53553. }
  53554. this._checkUniform(name);
  53555. this._textureArrays[name] = textures;
  53556. return this;
  53557. };
  53558. ShaderMaterial.prototype.setFloat = function (name, value) {
  53559. this._checkUniform(name);
  53560. this._floats[name] = value;
  53561. return this;
  53562. };
  53563. ShaderMaterial.prototype.setInt = function (name, value) {
  53564. this._checkUniform(name);
  53565. this._ints[name] = value;
  53566. return this;
  53567. };
  53568. ShaderMaterial.prototype.setFloats = function (name, value) {
  53569. this._checkUniform(name);
  53570. this._floatsArrays[name] = value;
  53571. return this;
  53572. };
  53573. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53574. this._checkUniform(name);
  53575. this._colors3[name] = value;
  53576. return this;
  53577. };
  53578. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53579. this._checkUniform(name);
  53580. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53581. color.toArray(arr, arr.length);
  53582. return arr;
  53583. }, []);
  53584. return this;
  53585. };
  53586. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53587. this._checkUniform(name);
  53588. this._colors4[name] = value;
  53589. return this;
  53590. };
  53591. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53592. this._checkUniform(name);
  53593. this._vectors2[name] = value;
  53594. return this;
  53595. };
  53596. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53597. this._checkUniform(name);
  53598. this._vectors3[name] = value;
  53599. return this;
  53600. };
  53601. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53602. this._checkUniform(name);
  53603. this._vectors4[name] = value;
  53604. return this;
  53605. };
  53606. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53607. this._checkUniform(name);
  53608. this._matrices[name] = value;
  53609. return this;
  53610. };
  53611. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53612. this._checkUniform(name);
  53613. this._matrices3x3[name] = value;
  53614. return this;
  53615. };
  53616. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53617. this._checkUniform(name);
  53618. this._matrices2x2[name] = value;
  53619. return this;
  53620. };
  53621. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53622. this._checkUniform(name);
  53623. this._vectors2Arrays[name] = value;
  53624. return this;
  53625. };
  53626. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53627. this._checkUniform(name);
  53628. this._vectors3Arrays[name] = value;
  53629. return this;
  53630. };
  53631. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53632. if (!mesh) {
  53633. return true;
  53634. }
  53635. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53636. return false;
  53637. }
  53638. return false;
  53639. };
  53640. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53641. var scene = this.getScene();
  53642. var engine = scene.getEngine();
  53643. if (!this.checkReadyOnEveryCall) {
  53644. if (this._renderId === scene.getRenderId()) {
  53645. if (this._checkCache(scene, mesh, useInstances)) {
  53646. return true;
  53647. }
  53648. }
  53649. }
  53650. // Instances
  53651. var defines = [];
  53652. var attribs = [];
  53653. var fallbacks = new BABYLON.EffectFallbacks();
  53654. if (useInstances) {
  53655. defines.push("#define INSTANCES");
  53656. }
  53657. for (var index = 0; index < this._options.defines.length; index++) {
  53658. defines.push(this._options.defines[index]);
  53659. }
  53660. for (var index = 0; index < this._options.attributes.length; index++) {
  53661. attribs.push(this._options.attributes[index]);
  53662. }
  53663. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53664. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53665. defines.push("#define VERTEXCOLOR");
  53666. }
  53667. // Bones
  53668. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53669. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53670. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53671. if (mesh.numBoneInfluencers > 4) {
  53672. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53673. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53674. }
  53675. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53676. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53677. fallbacks.addCPUSkinningFallback(0, mesh);
  53678. if (this._options.uniforms.indexOf("mBones") === -1) {
  53679. this._options.uniforms.push("mBones");
  53680. }
  53681. }
  53682. else {
  53683. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53684. }
  53685. // Textures
  53686. for (var name in this._textures) {
  53687. if (!this._textures[name].isReady()) {
  53688. return false;
  53689. }
  53690. }
  53691. // Alpha test
  53692. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53693. defines.push("#define ALPHATEST");
  53694. }
  53695. var previousEffect = this._effect;
  53696. var join = defines.join("\n");
  53697. this._effect = engine.createEffect(this._shaderPath, {
  53698. attributes: attribs,
  53699. uniformsNames: this._options.uniforms,
  53700. uniformBuffersNames: this._options.uniformBuffers,
  53701. samplers: this._options.samplers,
  53702. defines: join,
  53703. fallbacks: fallbacks,
  53704. onCompiled: this.onCompiled,
  53705. onError: this.onError
  53706. }, engine);
  53707. if (!this._effect.isReady()) {
  53708. return false;
  53709. }
  53710. if (previousEffect !== this._effect) {
  53711. scene.resetCachedMaterial();
  53712. }
  53713. this._renderId = scene.getRenderId();
  53714. return true;
  53715. };
  53716. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53717. var scene = this.getScene();
  53718. if (!this._effect) {
  53719. return;
  53720. }
  53721. if (this._options.uniforms.indexOf("world") !== -1) {
  53722. this._effect.setMatrix("world", world);
  53723. }
  53724. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53725. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53726. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53727. }
  53728. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53729. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53730. }
  53731. };
  53732. ShaderMaterial.prototype.bind = function (world, mesh) {
  53733. // Std values
  53734. this.bindOnlyWorldMatrix(world);
  53735. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53736. if (this._options.uniforms.indexOf("view") !== -1) {
  53737. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53738. }
  53739. if (this._options.uniforms.indexOf("projection") !== -1) {
  53740. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53741. }
  53742. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53743. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53744. }
  53745. // Bones
  53746. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53747. var name;
  53748. // Texture
  53749. for (name in this._textures) {
  53750. this._effect.setTexture(name, this._textures[name]);
  53751. }
  53752. // Texture arrays
  53753. for (name in this._textureArrays) {
  53754. this._effect.setTextureArray(name, this._textureArrays[name]);
  53755. }
  53756. // Int
  53757. for (name in this._ints) {
  53758. this._effect.setInt(name, this._ints[name]);
  53759. }
  53760. // Float
  53761. for (name in this._floats) {
  53762. this._effect.setFloat(name, this._floats[name]);
  53763. }
  53764. // Floats
  53765. for (name in this._floatsArrays) {
  53766. this._effect.setArray(name, this._floatsArrays[name]);
  53767. }
  53768. // Color3
  53769. for (name in this._colors3) {
  53770. this._effect.setColor3(name, this._colors3[name]);
  53771. }
  53772. for (name in this._colors3Arrays) {
  53773. this._effect.setArray3(name, this._colors3Arrays[name]);
  53774. }
  53775. // Color4
  53776. for (name in this._colors4) {
  53777. var color = this._colors4[name];
  53778. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53779. }
  53780. // Vector2
  53781. for (name in this._vectors2) {
  53782. this._effect.setVector2(name, this._vectors2[name]);
  53783. }
  53784. // Vector3
  53785. for (name in this._vectors3) {
  53786. this._effect.setVector3(name, this._vectors3[name]);
  53787. }
  53788. // Vector4
  53789. for (name in this._vectors4) {
  53790. this._effect.setVector4(name, this._vectors4[name]);
  53791. }
  53792. // Matrix
  53793. for (name in this._matrices) {
  53794. this._effect.setMatrix(name, this._matrices[name]);
  53795. }
  53796. // Matrix 3x3
  53797. for (name in this._matrices3x3) {
  53798. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53799. }
  53800. // Matrix 2x2
  53801. for (name in this._matrices2x2) {
  53802. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53803. }
  53804. // Vector2Array
  53805. for (name in this._vectors2Arrays) {
  53806. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53807. }
  53808. // Vector3Array
  53809. for (name in this._vectors3Arrays) {
  53810. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53811. }
  53812. }
  53813. this._afterBind(mesh);
  53814. };
  53815. ShaderMaterial.prototype.getActiveTextures = function () {
  53816. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53817. for (var name in this._textures) {
  53818. activeTextures.push(this._textures[name]);
  53819. }
  53820. for (var name in this._textureArrays) {
  53821. var array = this._textureArrays[name];
  53822. for (var index = 0; index < array.length; index++) {
  53823. activeTextures.push(array[index]);
  53824. }
  53825. }
  53826. return activeTextures;
  53827. };
  53828. ShaderMaterial.prototype.hasTexture = function (texture) {
  53829. if (_super.prototype.hasTexture.call(this, texture)) {
  53830. return true;
  53831. }
  53832. for (var name in this._textures) {
  53833. if (this._textures[name] === texture) {
  53834. return true;
  53835. }
  53836. }
  53837. for (var name in this._textureArrays) {
  53838. var array = this._textureArrays[name];
  53839. for (var index = 0; index < array.length; index++) {
  53840. if (array[index] === texture) {
  53841. return true;
  53842. }
  53843. }
  53844. }
  53845. return false;
  53846. };
  53847. ShaderMaterial.prototype.clone = function (name) {
  53848. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53849. return newShaderMaterial;
  53850. };
  53851. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53852. if (forceDisposeTextures) {
  53853. var name;
  53854. for (name in this._textures) {
  53855. this._textures[name].dispose();
  53856. }
  53857. for (name in this._textureArrays) {
  53858. var array = this._textureArrays[name];
  53859. for (var index = 0; index < array.length; index++) {
  53860. array[index].dispose();
  53861. }
  53862. }
  53863. }
  53864. this._textures = {};
  53865. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53866. };
  53867. ShaderMaterial.prototype.serialize = function () {
  53868. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53869. serializationObject.customType = "BABYLON.ShaderMaterial";
  53870. serializationObject.options = this._options;
  53871. serializationObject.shaderPath = this._shaderPath;
  53872. var name;
  53873. // Texture
  53874. serializationObject.textures = {};
  53875. for (name in this._textures) {
  53876. serializationObject.textures[name] = this._textures[name].serialize();
  53877. }
  53878. // Texture arrays
  53879. serializationObject.textureArrays = {};
  53880. for (name in this._textureArrays) {
  53881. serializationObject.textureArrays[name] = [];
  53882. var array = this._textureArrays[name];
  53883. for (var index = 0; index < array.length; index++) {
  53884. serializationObject.textureArrays[name].push(array[index].serialize());
  53885. }
  53886. }
  53887. // Float
  53888. serializationObject.floats = {};
  53889. for (name in this._floats) {
  53890. serializationObject.floats[name] = this._floats[name];
  53891. }
  53892. // Float s
  53893. serializationObject.FloatArrays = {};
  53894. for (name in this._floatsArrays) {
  53895. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53896. }
  53897. // Color3
  53898. serializationObject.colors3 = {};
  53899. for (name in this._colors3) {
  53900. serializationObject.colors3[name] = this._colors3[name].asArray();
  53901. }
  53902. // Color3 array
  53903. serializationObject.colors3Arrays = {};
  53904. for (name in this._colors3Arrays) {
  53905. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53906. }
  53907. // Color4
  53908. serializationObject.colors4 = {};
  53909. for (name in this._colors4) {
  53910. serializationObject.colors4[name] = this._colors4[name].asArray();
  53911. }
  53912. // Vector2
  53913. serializationObject.vectors2 = {};
  53914. for (name in this._vectors2) {
  53915. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53916. }
  53917. // Vector3
  53918. serializationObject.vectors3 = {};
  53919. for (name in this._vectors3) {
  53920. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53921. }
  53922. // Vector4
  53923. serializationObject.vectors4 = {};
  53924. for (name in this._vectors4) {
  53925. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53926. }
  53927. // Matrix
  53928. serializationObject.matrices = {};
  53929. for (name in this._matrices) {
  53930. serializationObject.matrices[name] = this._matrices[name].asArray();
  53931. }
  53932. // Matrix 3x3
  53933. serializationObject.matrices3x3 = {};
  53934. for (name in this._matrices3x3) {
  53935. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53936. }
  53937. // Matrix 2x2
  53938. serializationObject.matrices2x2 = {};
  53939. for (name in this._matrices2x2) {
  53940. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53941. }
  53942. // Vector2Array
  53943. serializationObject.vectors2Arrays = {};
  53944. for (name in this._vectors2Arrays) {
  53945. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53946. }
  53947. // Vector3Array
  53948. serializationObject.vectors3Arrays = {};
  53949. for (name in this._vectors3Arrays) {
  53950. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53951. }
  53952. return serializationObject;
  53953. };
  53954. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53955. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53956. var name;
  53957. // Texture
  53958. for (name in source.textures) {
  53959. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53960. }
  53961. // Texture arrays
  53962. for (name in source.textureArrays) {
  53963. var array = source.textureArrays[name];
  53964. var textureArray = new Array();
  53965. for (var index = 0; index < array.length; index++) {
  53966. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53967. }
  53968. material.setTextureArray(name, textureArray);
  53969. }
  53970. // Float
  53971. for (name in source.floats) {
  53972. material.setFloat(name, source.floats[name]);
  53973. }
  53974. // Float s
  53975. for (name in source.floatsArrays) {
  53976. material.setFloats(name, source.floatsArrays[name]);
  53977. }
  53978. // Color3
  53979. for (name in source.colors3) {
  53980. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53981. }
  53982. // Color3 arrays
  53983. for (name in source.colors3Arrays) {
  53984. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53985. if (i % 3 === 0) {
  53986. arr.push([num]);
  53987. }
  53988. else {
  53989. arr[arr.length - 1].push(num);
  53990. }
  53991. return arr;
  53992. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53993. material.setColor3Array(name, colors);
  53994. }
  53995. // Color4
  53996. for (name in source.colors4) {
  53997. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53998. }
  53999. // Vector2
  54000. for (name in source.vectors2) {
  54001. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54002. }
  54003. // Vector3
  54004. for (name in source.vectors3) {
  54005. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54006. }
  54007. // Vector4
  54008. for (name in source.vectors4) {
  54009. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54010. }
  54011. // Matrix
  54012. for (name in source.matrices) {
  54013. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54014. }
  54015. // Matrix 3x3
  54016. for (name in source.matrices3x3) {
  54017. material.setMatrix3x3(name, source.matrices3x3[name]);
  54018. }
  54019. // Matrix 2x2
  54020. for (name in source.matrices2x2) {
  54021. material.setMatrix2x2(name, source.matrices2x2[name]);
  54022. }
  54023. // Vector2Array
  54024. for (name in source.vectors2Arrays) {
  54025. material.setArray2(name, source.vectors2Arrays[name]);
  54026. }
  54027. // Vector3Array
  54028. for (name in source.vectors3Arrays) {
  54029. material.setArray3(name, source.vectors3Arrays[name]);
  54030. }
  54031. return material;
  54032. };
  54033. return ShaderMaterial;
  54034. }(BABYLON.Material));
  54035. BABYLON.ShaderMaterial = ShaderMaterial;
  54036. })(BABYLON || (BABYLON = {}));
  54037. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54038. var BABYLON;
  54039. (function (BABYLON) {
  54040. var GroundMesh = /** @class */ (function (_super) {
  54041. __extends(GroundMesh, _super);
  54042. function GroundMesh(name, scene) {
  54043. var _this = _super.call(this, name, scene) || this;
  54044. _this.generateOctree = false;
  54045. return _this;
  54046. }
  54047. GroundMesh.prototype.getClassName = function () {
  54048. return "GroundMesh";
  54049. };
  54050. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54051. get: function () {
  54052. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54053. },
  54054. enumerable: true,
  54055. configurable: true
  54056. });
  54057. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54058. get: function () {
  54059. return this._subdivisionsX;
  54060. },
  54061. enumerable: true,
  54062. configurable: true
  54063. });
  54064. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54065. get: function () {
  54066. return this._subdivisionsY;
  54067. },
  54068. enumerable: true,
  54069. configurable: true
  54070. });
  54071. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54072. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54073. this._subdivisionsX = chunksCount;
  54074. this._subdivisionsY = chunksCount;
  54075. this.subdivide(chunksCount);
  54076. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54077. };
  54078. /**
  54079. * Returns a height (y) value in the Worl system :
  54080. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54081. * Returns the ground y position if (x, z) are outside the ground surface.
  54082. */
  54083. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54084. var world = this.getWorldMatrix();
  54085. var invMat = BABYLON.Tmp.Matrix[5];
  54086. world.invertToRef(invMat);
  54087. var tmpVect = BABYLON.Tmp.Vector3[8];
  54088. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54089. x = tmpVect.x;
  54090. z = tmpVect.z;
  54091. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54092. return this.position.y;
  54093. }
  54094. if (!this._heightQuads || this._heightQuads.length == 0) {
  54095. this._initHeightQuads();
  54096. this._computeHeightQuads();
  54097. }
  54098. var facet = this._getFacetAt(x, z);
  54099. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54100. // return y in the World system
  54101. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54102. return tmpVect.y;
  54103. };
  54104. /**
  54105. * Returns a normalized vector (Vector3) orthogonal to the ground
  54106. * at the ground coordinates (x, z) expressed in the World system.
  54107. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54108. */
  54109. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54110. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54111. this.getNormalAtCoordinatesToRef(x, z, normal);
  54112. return normal;
  54113. };
  54114. /**
  54115. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54116. * at the ground coordinates (x, z) expressed in the World system.
  54117. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54118. * Returns the GroundMesh.
  54119. */
  54120. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54121. var world = this.getWorldMatrix();
  54122. var tmpMat = BABYLON.Tmp.Matrix[5];
  54123. world.invertToRef(tmpMat);
  54124. var tmpVect = BABYLON.Tmp.Vector3[8];
  54125. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54126. x = tmpVect.x;
  54127. z = tmpVect.z;
  54128. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54129. return this;
  54130. }
  54131. if (!this._heightQuads || this._heightQuads.length == 0) {
  54132. this._initHeightQuads();
  54133. this._computeHeightQuads();
  54134. }
  54135. var facet = this._getFacetAt(x, z);
  54136. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54137. return this;
  54138. };
  54139. /**
  54140. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54141. * if the ground has been updated.
  54142. * This can be used in the render loop.
  54143. * Returns the GroundMesh.
  54144. */
  54145. GroundMesh.prototype.updateCoordinateHeights = function () {
  54146. if (!this._heightQuads || this._heightQuads.length == 0) {
  54147. this._initHeightQuads();
  54148. }
  54149. this._computeHeightQuads();
  54150. return this;
  54151. };
  54152. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54153. GroundMesh.prototype._getFacetAt = function (x, z) {
  54154. // retrieve col and row from x, z coordinates in the ground local system
  54155. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54156. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54157. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54158. var facet;
  54159. if (z < quad.slope.x * x + quad.slope.y) {
  54160. facet = quad.facet1;
  54161. }
  54162. else {
  54163. facet = quad.facet2;
  54164. }
  54165. return facet;
  54166. };
  54167. // Creates and populates the heightMap array with "facet" elements :
  54168. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54169. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54170. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54171. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54172. // Returns the GroundMesh.
  54173. GroundMesh.prototype._initHeightQuads = function () {
  54174. var subdivisionsX = this._subdivisionsX;
  54175. var subdivisionsY = this._subdivisionsY;
  54176. this._heightQuads = new Array();
  54177. for (var row = 0; row < subdivisionsY; row++) {
  54178. for (var col = 0; col < subdivisionsX; col++) {
  54179. 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) };
  54180. this._heightQuads[row * subdivisionsX + col] = quad;
  54181. }
  54182. }
  54183. return this;
  54184. };
  54185. // Compute each quad element values and update the the heightMap array :
  54186. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54187. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54188. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54189. // Returns the GroundMesh.
  54190. GroundMesh.prototype._computeHeightQuads = function () {
  54191. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54192. if (!positions) {
  54193. return this;
  54194. }
  54195. var v1 = BABYLON.Tmp.Vector3[3];
  54196. var v2 = BABYLON.Tmp.Vector3[2];
  54197. var v3 = BABYLON.Tmp.Vector3[1];
  54198. var v4 = BABYLON.Tmp.Vector3[0];
  54199. var v1v2 = BABYLON.Tmp.Vector3[4];
  54200. var v1v3 = BABYLON.Tmp.Vector3[5];
  54201. var v1v4 = BABYLON.Tmp.Vector3[6];
  54202. var norm1 = BABYLON.Tmp.Vector3[7];
  54203. var norm2 = BABYLON.Tmp.Vector3[8];
  54204. var i = 0;
  54205. var j = 0;
  54206. var k = 0;
  54207. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54208. var h = 0;
  54209. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54210. var d2 = 0;
  54211. var subdivisionsX = this._subdivisionsX;
  54212. var subdivisionsY = this._subdivisionsY;
  54213. for (var row = 0; row < subdivisionsY; row++) {
  54214. for (var col = 0; col < subdivisionsX; col++) {
  54215. i = col * 3;
  54216. j = row * (subdivisionsX + 1) * 3;
  54217. k = (row + 1) * (subdivisionsX + 1) * 3;
  54218. v1.x = positions[j + i];
  54219. v1.y = positions[j + i + 1];
  54220. v1.z = positions[j + i + 2];
  54221. v2.x = positions[j + i + 3];
  54222. v2.y = positions[j + i + 4];
  54223. v2.z = positions[j + i + 5];
  54224. v3.x = positions[k + i];
  54225. v3.y = positions[k + i + 1];
  54226. v3.z = positions[k + i + 2];
  54227. v4.x = positions[k + i + 3];
  54228. v4.y = positions[k + i + 4];
  54229. v4.z = positions[k + i + 5];
  54230. // 2D slope V1V4
  54231. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54232. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54233. // facet equations :
  54234. // we compute each facet normal vector
  54235. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54236. // we compute the value d by applying the equation to v1 which belongs to the plane
  54237. // then we store the facet equation in a Vector4
  54238. v2.subtractToRef(v1, v1v2);
  54239. v3.subtractToRef(v1, v1v3);
  54240. v4.subtractToRef(v1, v1v4);
  54241. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54242. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54243. norm1.normalize();
  54244. norm2.normalize();
  54245. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54246. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54247. var quad = this._heightQuads[row * subdivisionsX + col];
  54248. quad.slope.copyFromFloats(cd, h);
  54249. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54250. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54251. }
  54252. }
  54253. return this;
  54254. };
  54255. GroundMesh.prototype.serialize = function (serializationObject) {
  54256. _super.prototype.serialize.call(this, serializationObject);
  54257. serializationObject.subdivisionsX = this._subdivisionsX;
  54258. serializationObject.subdivisionsY = this._subdivisionsY;
  54259. serializationObject.minX = this._minX;
  54260. serializationObject.maxX = this._maxX;
  54261. serializationObject.minZ = this._minZ;
  54262. serializationObject.maxZ = this._maxZ;
  54263. serializationObject.width = this._width;
  54264. serializationObject.height = this._height;
  54265. };
  54266. GroundMesh.Parse = function (parsedMesh, scene) {
  54267. var result = new GroundMesh(parsedMesh.name, scene);
  54268. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54269. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54270. result._minX = parsedMesh.minX;
  54271. result._maxX = parsedMesh.maxX;
  54272. result._minZ = parsedMesh.minZ;
  54273. result._maxZ = parsedMesh.maxZ;
  54274. result._width = parsedMesh.width;
  54275. result._height = parsedMesh.height;
  54276. return result;
  54277. };
  54278. return GroundMesh;
  54279. }(BABYLON.Mesh));
  54280. BABYLON.GroundMesh = GroundMesh;
  54281. })(BABYLON || (BABYLON = {}));
  54282. //# sourceMappingURL=babylon.groundMesh.js.map
  54283. var BABYLON;
  54284. (function (BABYLON) {
  54285. /**
  54286. * Creates an instance based on a source mesh.
  54287. */
  54288. var InstancedMesh = /** @class */ (function (_super) {
  54289. __extends(InstancedMesh, _super);
  54290. function InstancedMesh(name, source) {
  54291. var _this = _super.call(this, name, source.getScene()) || this;
  54292. source.instances.push(_this);
  54293. _this._sourceMesh = source;
  54294. _this.position.copyFrom(source.position);
  54295. _this.rotation.copyFrom(source.rotation);
  54296. _this.scaling.copyFrom(source.scaling);
  54297. if (source.rotationQuaternion) {
  54298. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54299. }
  54300. _this.infiniteDistance = source.infiniteDistance;
  54301. _this.setPivotMatrix(source.getPivotMatrix());
  54302. _this.refreshBoundingInfo();
  54303. _this._syncSubMeshes();
  54304. return _this;
  54305. }
  54306. /**
  54307. * Returns the string "InstancedMesh".
  54308. */
  54309. InstancedMesh.prototype.getClassName = function () {
  54310. return "InstancedMesh";
  54311. };
  54312. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54313. // Methods
  54314. get: function () {
  54315. return this._sourceMesh.receiveShadows;
  54316. },
  54317. enumerable: true,
  54318. configurable: true
  54319. });
  54320. Object.defineProperty(InstancedMesh.prototype, "material", {
  54321. get: function () {
  54322. return this._sourceMesh.material;
  54323. },
  54324. enumerable: true,
  54325. configurable: true
  54326. });
  54327. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54328. get: function () {
  54329. return this._sourceMesh.visibility;
  54330. },
  54331. enumerable: true,
  54332. configurable: true
  54333. });
  54334. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54335. get: function () {
  54336. return this._sourceMesh.skeleton;
  54337. },
  54338. enumerable: true,
  54339. configurable: true
  54340. });
  54341. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54342. get: function () {
  54343. return this._sourceMesh.renderingGroupId;
  54344. },
  54345. enumerable: true,
  54346. configurable: true
  54347. });
  54348. /**
  54349. * Returns the total number of vertices (integer).
  54350. */
  54351. InstancedMesh.prototype.getTotalVertices = function () {
  54352. return this._sourceMesh.getTotalVertices();
  54353. };
  54354. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54355. get: function () {
  54356. return this._sourceMesh;
  54357. },
  54358. enumerable: true,
  54359. configurable: true
  54360. });
  54361. /**
  54362. * Is this node ready to be used/rendered
  54363. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54364. * @return {boolean} is it ready
  54365. */
  54366. InstancedMesh.prototype.isReady = function (completeCheck) {
  54367. if (completeCheck === void 0) { completeCheck = false; }
  54368. return this._sourceMesh.isReady(completeCheck, true);
  54369. };
  54370. /**
  54371. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54372. */
  54373. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54374. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54375. };
  54376. /**
  54377. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54378. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54379. * The `data` are either a numeric array either a Float32Array.
  54380. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54381. * 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).
  54382. * Note that a new underlying VertexBuffer object is created each call.
  54383. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54384. *
  54385. * Possible `kind` values :
  54386. * - BABYLON.VertexBuffer.PositionKind
  54387. * - BABYLON.VertexBuffer.UVKind
  54388. * - BABYLON.VertexBuffer.UV2Kind
  54389. * - BABYLON.VertexBuffer.UV3Kind
  54390. * - BABYLON.VertexBuffer.UV4Kind
  54391. * - BABYLON.VertexBuffer.UV5Kind
  54392. * - BABYLON.VertexBuffer.UV6Kind
  54393. * - BABYLON.VertexBuffer.ColorKind
  54394. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54395. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54396. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54397. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54398. *
  54399. * Returns the Mesh.
  54400. */
  54401. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54402. if (this.sourceMesh) {
  54403. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54404. }
  54405. return this.sourceMesh;
  54406. };
  54407. /**
  54408. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54409. * If the mesh has no geometry, it is simply returned as it is.
  54410. * The `data` are either a numeric array either a Float32Array.
  54411. * No new underlying VertexBuffer object is created.
  54412. * 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.
  54413. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54414. *
  54415. * Possible `kind` values :
  54416. * - BABYLON.VertexBuffer.PositionKind
  54417. * - BABYLON.VertexBuffer.UVKind
  54418. * - BABYLON.VertexBuffer.UV2Kind
  54419. * - BABYLON.VertexBuffer.UV3Kind
  54420. * - BABYLON.VertexBuffer.UV4Kind
  54421. * - BABYLON.VertexBuffer.UV5Kind
  54422. * - BABYLON.VertexBuffer.UV6Kind
  54423. * - BABYLON.VertexBuffer.ColorKind
  54424. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54425. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54426. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54427. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54428. *
  54429. * Returns the Mesh.
  54430. */
  54431. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54432. if (this.sourceMesh) {
  54433. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54434. }
  54435. return this.sourceMesh;
  54436. };
  54437. /**
  54438. * Sets the mesh indices.
  54439. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54440. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54441. * This method creates a new index buffer each call.
  54442. * Returns the Mesh.
  54443. */
  54444. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54445. if (totalVertices === void 0) { totalVertices = null; }
  54446. if (this.sourceMesh) {
  54447. this.sourceMesh.setIndices(indices, totalVertices);
  54448. }
  54449. return this.sourceMesh;
  54450. };
  54451. /**
  54452. * Boolean : True if the mesh owns the requested kind of data.
  54453. */
  54454. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54455. return this._sourceMesh.isVerticesDataPresent(kind);
  54456. };
  54457. /**
  54458. * Returns an array of indices (IndicesArray).
  54459. */
  54460. InstancedMesh.prototype.getIndices = function () {
  54461. return this._sourceMesh.getIndices();
  54462. };
  54463. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54464. get: function () {
  54465. return this._sourceMesh._positions;
  54466. },
  54467. enumerable: true,
  54468. configurable: true
  54469. });
  54470. /**
  54471. * Sets a new updated BoundingInfo to the mesh.
  54472. * Returns the mesh.
  54473. */
  54474. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54475. var meshBB = this._sourceMesh.getBoundingInfo();
  54476. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54477. this._updateBoundingInfo();
  54478. return this;
  54479. };
  54480. InstancedMesh.prototype._preActivate = function () {
  54481. if (this._currentLOD) {
  54482. this._currentLOD._preActivate();
  54483. }
  54484. return this;
  54485. };
  54486. InstancedMesh.prototype._activate = function (renderId) {
  54487. if (this._currentLOD) {
  54488. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54489. }
  54490. return this;
  54491. };
  54492. /**
  54493. * Returns the current associated LOD AbstractMesh.
  54494. */
  54495. InstancedMesh.prototype.getLOD = function (camera) {
  54496. if (!camera) {
  54497. return this;
  54498. }
  54499. var boundingInfo = this.getBoundingInfo();
  54500. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54501. if (this._currentLOD === this.sourceMesh) {
  54502. return this;
  54503. }
  54504. return this._currentLOD;
  54505. };
  54506. InstancedMesh.prototype._syncSubMeshes = function () {
  54507. this.releaseSubMeshes();
  54508. if (this._sourceMesh.subMeshes) {
  54509. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54510. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54511. }
  54512. }
  54513. return this;
  54514. };
  54515. InstancedMesh.prototype._generatePointsArray = function () {
  54516. return this._sourceMesh._generatePointsArray();
  54517. };
  54518. /**
  54519. * Creates a new InstancedMesh from the current mesh.
  54520. * - name (string) : the cloned mesh name
  54521. * - newParent (optional Node) : the optional Node to parent the clone to.
  54522. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54523. *
  54524. * Returns the clone.
  54525. */
  54526. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54527. var result = this._sourceMesh.createInstance(name);
  54528. // Deep copy
  54529. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54530. // Bounding info
  54531. this.refreshBoundingInfo();
  54532. // Parent
  54533. if (newParent) {
  54534. result.parent = newParent;
  54535. }
  54536. if (!doNotCloneChildren) {
  54537. // Children
  54538. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54539. var mesh = this.getScene().meshes[index];
  54540. if (mesh.parent === this) {
  54541. mesh.clone(mesh.name, result);
  54542. }
  54543. }
  54544. }
  54545. result.computeWorldMatrix(true);
  54546. return result;
  54547. };
  54548. /**
  54549. * Disposes the InstancedMesh.
  54550. * Returns nothing.
  54551. */
  54552. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  54553. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  54554. // Remove from mesh
  54555. var index = this._sourceMesh.instances.indexOf(this);
  54556. this._sourceMesh.instances.splice(index, 1);
  54557. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  54558. };
  54559. return InstancedMesh;
  54560. }(BABYLON.AbstractMesh));
  54561. BABYLON.InstancedMesh = InstancedMesh;
  54562. })(BABYLON || (BABYLON = {}));
  54563. //# sourceMappingURL=babylon.instancedMesh.js.map
  54564. var BABYLON;
  54565. (function (BABYLON) {
  54566. var LinesMesh = /** @class */ (function (_super) {
  54567. __extends(LinesMesh, _super);
  54568. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54569. if (scene === void 0) { scene = null; }
  54570. if (parent === void 0) { parent = null; }
  54571. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54572. _this.useVertexColor = useVertexColor;
  54573. _this.useVertexAlpha = useVertexAlpha;
  54574. _this.color = new BABYLON.Color3(1, 1, 1);
  54575. _this.alpha = 1;
  54576. if (source) {
  54577. _this.color = source.color.clone();
  54578. _this.alpha = source.alpha;
  54579. _this.useVertexColor = source.useVertexColor;
  54580. _this.useVertexAlpha = source.useVertexAlpha;
  54581. }
  54582. _this._intersectionThreshold = 0.1;
  54583. var defines = [];
  54584. var options = {
  54585. attributes: [BABYLON.VertexBuffer.PositionKind],
  54586. uniforms: ["world", "viewProjection"],
  54587. needAlphaBlending: true,
  54588. defines: defines
  54589. };
  54590. if (useVertexAlpha === false) {
  54591. options.needAlphaBlending = false;
  54592. }
  54593. if (!useVertexColor) {
  54594. options.uniforms.push("color");
  54595. }
  54596. else {
  54597. options.defines.push("#define VERTEXCOLOR");
  54598. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54599. }
  54600. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54601. return _this;
  54602. }
  54603. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54604. /**
  54605. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54606. * This margin is expressed in world space coordinates, so its value may vary.
  54607. * Default value is 0.1
  54608. * @returns the intersection Threshold value.
  54609. */
  54610. get: function () {
  54611. return this._intersectionThreshold;
  54612. },
  54613. /**
  54614. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54615. * This margin is expressed in world space coordinates, so its value may vary.
  54616. * @param value the new threshold to apply
  54617. */
  54618. set: function (value) {
  54619. if (this._intersectionThreshold === value) {
  54620. return;
  54621. }
  54622. this._intersectionThreshold = value;
  54623. if (this.geometry) {
  54624. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54625. }
  54626. },
  54627. enumerable: true,
  54628. configurable: true
  54629. });
  54630. /**
  54631. * Returns the string "LineMesh"
  54632. */
  54633. LinesMesh.prototype.getClassName = function () {
  54634. return "LinesMesh";
  54635. };
  54636. Object.defineProperty(LinesMesh.prototype, "material", {
  54637. get: function () {
  54638. return this._colorShader;
  54639. },
  54640. set: function (value) {
  54641. // Do nothing
  54642. },
  54643. enumerable: true,
  54644. configurable: true
  54645. });
  54646. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54647. get: function () {
  54648. return false;
  54649. },
  54650. enumerable: true,
  54651. configurable: true
  54652. });
  54653. LinesMesh.prototype.createInstance = function (name) {
  54654. throw new Error("LinesMeshes do not support createInstance.");
  54655. };
  54656. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54657. if (!this._geometry) {
  54658. return this;
  54659. }
  54660. // VBOs
  54661. this._geometry._bind(this._colorShader.getEffect());
  54662. // Color
  54663. if (!this.useVertexColor) {
  54664. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54665. }
  54666. return this;
  54667. };
  54668. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54669. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54670. return this;
  54671. }
  54672. var engine = this.getScene().getEngine();
  54673. // Draw order
  54674. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54675. return this;
  54676. };
  54677. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54678. this._colorShader.dispose();
  54679. _super.prototype.dispose.call(this, doNotRecurse);
  54680. };
  54681. /**
  54682. * Returns a new LineMesh object cloned from the current one.
  54683. */
  54684. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54685. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54686. };
  54687. return LinesMesh;
  54688. }(BABYLON.Mesh));
  54689. BABYLON.LinesMesh = LinesMesh;
  54690. })(BABYLON || (BABYLON = {}));
  54691. //# sourceMappingURL=babylon.linesMesh.js.map
  54692. var BABYLON;
  54693. (function (BABYLON) {
  54694. var MeshBuilder = /** @class */ (function () {
  54695. function MeshBuilder() {
  54696. }
  54697. MeshBuilder.updateSideOrientation = function (orientation) {
  54698. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54699. return BABYLON.Mesh.DOUBLESIDE;
  54700. }
  54701. if (orientation === undefined || orientation === null) {
  54702. return BABYLON.Mesh.FRONTSIDE;
  54703. }
  54704. return orientation;
  54705. };
  54706. /**
  54707. * Creates a box mesh.
  54708. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54709. * The parameter `size` sets the size (float) of each box side (default 1).
  54710. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54711. * 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).
  54712. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54713. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54714. * 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).
  54715. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54717. */
  54718. MeshBuilder.CreateBox = function (name, options, scene) {
  54719. if (scene === void 0) { scene = null; }
  54720. var box = new BABYLON.Mesh(name, scene);
  54721. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54722. box._originalBuilderSideOrientation = options.sideOrientation;
  54723. var vertexData = BABYLON.VertexData.CreateBox(options);
  54724. vertexData.applyToMesh(box, options.updatable);
  54725. return box;
  54726. };
  54727. /**
  54728. * Creates a sphere mesh.
  54729. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54730. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54731. * 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`).
  54732. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54733. * 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
  54734. * 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).
  54735. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54736. * 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).
  54737. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54739. */
  54740. MeshBuilder.CreateSphere = function (name, options, scene) {
  54741. var sphere = new BABYLON.Mesh(name, scene);
  54742. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54743. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54744. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54745. vertexData.applyToMesh(sphere, options.updatable);
  54746. return sphere;
  54747. };
  54748. /**
  54749. * Creates a plane polygonal mesh. By default, this is a disc.
  54750. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54751. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54752. * 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.
  54753. * 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
  54754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54755. * 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).
  54756. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54758. */
  54759. MeshBuilder.CreateDisc = function (name, options, scene) {
  54760. if (scene === void 0) { scene = null; }
  54761. var disc = new BABYLON.Mesh(name, scene);
  54762. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54763. disc._originalBuilderSideOrientation = options.sideOrientation;
  54764. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54765. vertexData.applyToMesh(disc, options.updatable);
  54766. return disc;
  54767. };
  54768. /**
  54769. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54770. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54771. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54772. * 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`).
  54773. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54774. * 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.
  54775. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54776. * 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).
  54777. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54778. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54779. */
  54780. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54781. var sphere = new BABYLON.Mesh(name, scene);
  54782. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54783. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54784. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54785. vertexData.applyToMesh(sphere, options.updatable);
  54786. return sphere;
  54787. };
  54788. ;
  54789. /**
  54790. * Creates a ribbon mesh.
  54791. * 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.
  54792. *
  54793. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54794. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54795. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54796. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54797. * 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.
  54798. * 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.
  54799. * 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
  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 optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54804. * 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.
  54805. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54806. * 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
  54807. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54808. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54810. */
  54811. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54812. if (scene === void 0) { scene = null; }
  54813. var pathArray = options.pathArray;
  54814. var closeArray = options.closeArray;
  54815. var closePath = options.closePath;
  54816. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54817. var instance = options.instance;
  54818. var updatable = options.updatable;
  54819. if (instance) {
  54820. // positionFunction : ribbon case
  54821. // only pathArray and sideOrientation parameters are taken into account for positions update
  54822. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54823. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54824. var positionFunction = function (positions) {
  54825. var minlg = pathArray[0].length;
  54826. var i = 0;
  54827. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54828. for (var si = 1; si <= ns; si++) {
  54829. for (var p = 0; p < pathArray.length; p++) {
  54830. var path = pathArray[p];
  54831. var l = path.length;
  54832. minlg = (minlg < l) ? minlg : l;
  54833. var j = 0;
  54834. while (j < minlg) {
  54835. positions[i] = path[j].x;
  54836. positions[i + 1] = path[j].y;
  54837. positions[i + 2] = path[j].z;
  54838. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54839. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54840. }
  54841. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54842. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54843. }
  54844. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54845. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54846. }
  54847. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54848. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54849. }
  54850. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54851. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54852. }
  54853. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54854. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54855. }
  54856. j++;
  54857. i += 3;
  54858. }
  54859. if (instance._closePath) {
  54860. positions[i] = path[0].x;
  54861. positions[i + 1] = path[0].y;
  54862. positions[i + 2] = path[0].z;
  54863. i += 3;
  54864. }
  54865. }
  54866. }
  54867. };
  54868. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54869. positionFunction(positions);
  54870. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54871. instance._boundingInfo.update(instance._worldMatrix);
  54872. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54873. if (options.colors) {
  54874. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54875. for (var c = 0; c < options.colors.length; c++) {
  54876. colors[c * 4] = options.colors[c].r;
  54877. colors[c * 4 + 1] = options.colors[c].g;
  54878. colors[c * 4 + 2] = options.colors[c].b;
  54879. colors[c * 4 + 3] = options.colors[c].a;
  54880. }
  54881. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54882. }
  54883. if (options.uvs) {
  54884. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54885. for (var i = 0; i < options.uvs.length; i++) {
  54886. uvs[i * 2] = options.uvs[i].x;
  54887. uvs[i * 2 + 1] = options.uvs[i].y;
  54888. }
  54889. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54890. }
  54891. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54892. var indices = instance.getIndices();
  54893. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54894. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54895. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54896. if (instance._closePath) {
  54897. var indexFirst = 0;
  54898. var indexLast = 0;
  54899. for (var p = 0; p < pathArray.length; p++) {
  54900. indexFirst = instance._idx[p] * 3;
  54901. if (p + 1 < pathArray.length) {
  54902. indexLast = (instance._idx[p + 1] - 1) * 3;
  54903. }
  54904. else {
  54905. indexLast = normals.length - 3;
  54906. }
  54907. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54908. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54909. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54910. normals[indexLast] = normals[indexFirst];
  54911. normals[indexLast + 1] = normals[indexFirst + 1];
  54912. normals[indexLast + 2] = normals[indexFirst + 2];
  54913. }
  54914. }
  54915. if (!(instance.areNormalsFrozen)) {
  54916. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54917. }
  54918. }
  54919. return instance;
  54920. }
  54921. else {
  54922. var ribbon = new BABYLON.Mesh(name, scene);
  54923. ribbon._originalBuilderSideOrientation = sideOrientation;
  54924. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54925. if (closePath) {
  54926. ribbon._idx = vertexData._idx;
  54927. }
  54928. ribbon._closePath = closePath;
  54929. ribbon._closeArray = closeArray;
  54930. vertexData.applyToMesh(ribbon, updatable);
  54931. return ribbon;
  54932. }
  54933. };
  54934. /**
  54935. * Creates a cylinder or a cone mesh.
  54936. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54937. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54938. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54939. * 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.
  54940. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54941. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54942. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54943. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54944. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54945. * 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).
  54946. * 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
  54947. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54948. * 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
  54949. * 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.
  54950. * If `enclose` is false, a ring surface is one element.
  54951. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54952. * 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
  54953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54954. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  54955. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54957. */
  54958. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54959. var cylinder = new BABYLON.Mesh(name, scene);
  54960. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54961. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54962. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54963. vertexData.applyToMesh(cylinder, options.updatable);
  54964. return cylinder;
  54965. };
  54966. /**
  54967. * Creates a torus mesh.
  54968. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54969. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54970. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54971. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54973. * 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).
  54974. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54975. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54976. */
  54977. MeshBuilder.CreateTorus = function (name, options, scene) {
  54978. var torus = new BABYLON.Mesh(name, scene);
  54979. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54980. torus._originalBuilderSideOrientation = options.sideOrientation;
  54981. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54982. vertexData.applyToMesh(torus, options.updatable);
  54983. return torus;
  54984. };
  54985. /**
  54986. * Creates a torus knot mesh.
  54987. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54988. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54989. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54990. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54991. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54992. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54993. * 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).
  54994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54996. */
  54997. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54998. var torusKnot = new BABYLON.Mesh(name, scene);
  54999. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55000. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55001. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55002. vertexData.applyToMesh(torusKnot, options.updatable);
  55003. return torusKnot;
  55004. };
  55005. /**
  55006. * Creates a line system mesh.
  55007. * A line system is a pool of many lines gathered in a single mesh.
  55008. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55009. * 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.
  55010. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55011. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55012. * 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
  55013. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55014. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55015. * 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
  55016. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55018. */
  55019. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55020. var instance = options.instance;
  55021. var lines = options.lines;
  55022. var colors = options.colors;
  55023. if (instance) {
  55024. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55025. var vertexColor;
  55026. var lineColors;
  55027. if (colors) {
  55028. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55029. }
  55030. var i = 0;
  55031. var c = 0;
  55032. for (var l = 0; l < lines.length; l++) {
  55033. var points = lines[l];
  55034. for (var p = 0; p < points.length; p++) {
  55035. positions[i] = points[p].x;
  55036. positions[i + 1] = points[p].y;
  55037. positions[i + 2] = points[p].z;
  55038. if (colors && vertexColor) {
  55039. lineColors = colors[l];
  55040. vertexColor[c] = lineColors[p].r;
  55041. vertexColor[c + 1] = lineColors[p].g;
  55042. vertexColor[c + 2] = lineColors[p].b;
  55043. vertexColor[c + 3] = lineColors[p].a;
  55044. c += 4;
  55045. }
  55046. i += 3;
  55047. }
  55048. }
  55049. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55050. if (colors && vertexColor) {
  55051. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55052. }
  55053. return instance;
  55054. }
  55055. // line system creation
  55056. var useVertexColor = (colors) ? true : false;
  55057. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55058. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55059. vertexData.applyToMesh(lineSystem, options.updatable);
  55060. return lineSystem;
  55061. };
  55062. /**
  55063. * Creates a line mesh.
  55064. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55065. * 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.
  55066. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55067. * The parameter `points` is an array successive Vector3.
  55068. * 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
  55069. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55070. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55071. * When updating an instance, remember that only point positions can change, not the number of points.
  55072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55073. */
  55074. MeshBuilder.CreateLines = function (name, options, scene) {
  55075. if (scene === void 0) { scene = null; }
  55076. var colors = (options.colors) ? [options.colors] : null;
  55077. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55078. return lines;
  55079. };
  55080. /**
  55081. * Creates a dashed line mesh.
  55082. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55083. * 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.
  55084. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55085. * The parameter `points` is an array successive Vector3.
  55086. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55087. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55088. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55089. * 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
  55090. * When updating an instance, remember that only point positions can change, not the number of points.
  55091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55092. */
  55093. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55094. if (scene === void 0) { scene = null; }
  55095. var points = options.points;
  55096. var instance = options.instance;
  55097. var gapSize = options.gapSize || 1;
  55098. var dashSize = options.dashSize || 3;
  55099. if (instance) {
  55100. var positionFunction = function (positions) {
  55101. var curvect = BABYLON.Vector3.Zero();
  55102. var nbSeg = positions.length / 6;
  55103. var lg = 0;
  55104. var nb = 0;
  55105. var shft = 0;
  55106. var dashshft = 0;
  55107. var curshft = 0;
  55108. var p = 0;
  55109. var i = 0;
  55110. var j = 0;
  55111. for (i = 0; i < points.length - 1; i++) {
  55112. points[i + 1].subtractToRef(points[i], curvect);
  55113. lg += curvect.length();
  55114. }
  55115. shft = lg / nbSeg;
  55116. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55117. for (i = 0; i < points.length - 1; i++) {
  55118. points[i + 1].subtractToRef(points[i], curvect);
  55119. nb = Math.floor(curvect.length() / shft);
  55120. curvect.normalize();
  55121. j = 0;
  55122. while (j < nb && p < positions.length) {
  55123. curshft = shft * j;
  55124. positions[p] = points[i].x + curshft * curvect.x;
  55125. positions[p + 1] = points[i].y + curshft * curvect.y;
  55126. positions[p + 2] = points[i].z + curshft * curvect.z;
  55127. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55128. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55129. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55130. p += 6;
  55131. j++;
  55132. }
  55133. }
  55134. while (p < positions.length) {
  55135. positions[p] = points[i].x;
  55136. positions[p + 1] = points[i].y;
  55137. positions[p + 2] = points[i].z;
  55138. p += 3;
  55139. }
  55140. };
  55141. instance.updateMeshPositions(positionFunction, false);
  55142. return instance;
  55143. }
  55144. // dashed lines creation
  55145. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55146. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55147. vertexData.applyToMesh(dashedLines, options.updatable);
  55148. dashedLines.dashSize = dashSize;
  55149. dashedLines.gapSize = gapSize;
  55150. return dashedLines;
  55151. };
  55152. /**
  55153. * Creates an extruded shape mesh.
  55154. * 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.
  55155. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55156. *
  55157. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55158. * 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
  55159. * extruded along the Z axis.
  55160. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55161. * 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.
  55162. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55163. * 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
  55164. * 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
  55165. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55167. * 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).
  55168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55169. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55170. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55171. */
  55172. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55173. if (scene === void 0) { scene = null; }
  55174. var path = options.path;
  55175. var shape = options.shape;
  55176. var scale = options.scale || 1;
  55177. var rotation = options.rotation || 0;
  55178. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55179. var updatable = options.updatable;
  55180. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55181. var instance = options.instance || null;
  55182. var invertUV = options.invertUV || false;
  55183. 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);
  55184. };
  55185. /**
  55186. * Creates an custom extruded shape mesh.
  55187. * 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.
  55188. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55189. *
  55190. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55191. * 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
  55192. * extruded along the Z axis.
  55193. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55194. * 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
  55195. * and the distance of this point from the begining of the path :
  55196. * ```javascript
  55197. * var rotationFunction = function(i, distance) {
  55198. * // do things
  55199. * return rotationValue; }
  55200. * ```
  55201. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55202. * 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
  55203. * and the distance of this point from the begining of the path :
  55204. * ```javascript
  55205. * var scaleFunction = function(i, distance) {
  55206. * // do things
  55207. * return scaleValue;}
  55208. * ```
  55209. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55210. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55211. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55212. * 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
  55213. * 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
  55214. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55215. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55216. * 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).
  55217. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55218. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55220. */
  55221. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55222. var path = options.path;
  55223. var shape = options.shape;
  55224. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55225. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55226. var ribbonCloseArray = options.ribbonCloseArray || false;
  55227. var ribbonClosePath = options.ribbonClosePath || false;
  55228. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55229. var updatable = options.updatable;
  55230. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55231. var instance = options.instance;
  55232. var invertUV = options.invertUV || false;
  55233. 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);
  55234. };
  55235. /**
  55236. * Creates lathe mesh.
  55237. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55238. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55239. *
  55240. * 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
  55241. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55242. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55243. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55244. * 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.
  55245. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55246. * 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
  55247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55248. * 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).
  55249. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55250. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55252. */
  55253. MeshBuilder.CreateLathe = function (name, options, scene) {
  55254. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55255. var closed = (options.closed === undefined) ? true : options.closed;
  55256. var shape = options.shape;
  55257. var radius = options.radius || 1;
  55258. var tessellation = options.tessellation || 64;
  55259. var updatable = options.updatable;
  55260. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55261. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55262. var pi2 = Math.PI * 2;
  55263. var paths = new Array();
  55264. var invertUV = options.invertUV || false;
  55265. var i = 0;
  55266. var p = 0;
  55267. var step = pi2 / tessellation * arc;
  55268. var rotated;
  55269. var path = new Array();
  55270. ;
  55271. for (i = 0; i <= tessellation; i++) {
  55272. var path = [];
  55273. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55274. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55275. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55276. }
  55277. for (p = 0; p < shape.length; p++) {
  55278. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55279. path.push(rotated);
  55280. }
  55281. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55282. 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));
  55283. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55284. }
  55285. paths.push(path);
  55286. }
  55287. // lathe ribbon
  55288. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55289. return lathe;
  55290. };
  55291. /**
  55292. * Creates a plane mesh.
  55293. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55294. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55295. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55296. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55297. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55298. * 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).
  55299. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55301. */
  55302. MeshBuilder.CreatePlane = function (name, options, scene) {
  55303. var plane = new BABYLON.Mesh(name, scene);
  55304. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55305. plane._originalBuilderSideOrientation = options.sideOrientation;
  55306. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55307. vertexData.applyToMesh(plane, options.updatable);
  55308. if (options.sourcePlane) {
  55309. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55310. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55311. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55312. plane.rotate(vectorProduct, product);
  55313. }
  55314. return plane;
  55315. };
  55316. /**
  55317. * Creates a ground mesh.
  55318. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55319. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55320. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55321. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55322. */
  55323. MeshBuilder.CreateGround = function (name, options, scene) {
  55324. var ground = new BABYLON.GroundMesh(name, scene);
  55325. ground._setReady(false);
  55326. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55327. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55328. ground._width = options.width || 1;
  55329. ground._height = options.height || 1;
  55330. ground._maxX = ground._width / 2;
  55331. ground._maxZ = ground._height / 2;
  55332. ground._minX = -ground._maxX;
  55333. ground._minZ = -ground._maxZ;
  55334. var vertexData = BABYLON.VertexData.CreateGround(options);
  55335. vertexData.applyToMesh(ground, options.updatable);
  55336. ground._setReady(true);
  55337. return ground;
  55338. };
  55339. /**
  55340. * Creates a tiled ground mesh.
  55341. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55342. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55343. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55344. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55345. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55346. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55347. * numbers of subdivisions on the ground width and height of each tile.
  55348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55349. */
  55350. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55351. var tiledGround = new BABYLON.Mesh(name, scene);
  55352. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55353. vertexData.applyToMesh(tiledGround, options.updatable);
  55354. return tiledGround;
  55355. };
  55356. /**
  55357. * Creates a ground mesh from a height map.
  55358. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55359. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55360. * The parameter `url` sets the URL of the height map image resource.
  55361. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55362. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55363. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55364. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55365. * 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.
  55366. * 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).
  55367. * This function is passed the newly built mesh :
  55368. * ```javascript
  55369. * function(mesh) { // do things
  55370. * return; }
  55371. * ```
  55372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55373. */
  55374. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55375. var width = options.width || 10.0;
  55376. var height = options.height || 10.0;
  55377. var subdivisions = options.subdivisions || 1 | 0;
  55378. var minHeight = options.minHeight || 0.0;
  55379. var maxHeight = options.maxHeight || 1.0;
  55380. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55381. var updatable = options.updatable;
  55382. var onReady = options.onReady;
  55383. var ground = new BABYLON.GroundMesh(name, scene);
  55384. ground._subdivisionsX = subdivisions;
  55385. ground._subdivisionsY = subdivisions;
  55386. ground._width = width;
  55387. ground._height = height;
  55388. ground._maxX = ground._width / 2.0;
  55389. ground._maxZ = ground._height / 2.0;
  55390. ground._minX = -ground._maxX;
  55391. ground._minZ = -ground._maxZ;
  55392. ground._setReady(false);
  55393. var onload = function (img) {
  55394. // Getting height map data
  55395. var canvas = document.createElement("canvas");
  55396. var context = canvas.getContext("2d");
  55397. if (!context) {
  55398. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55399. }
  55400. if (scene.isDisposed) {
  55401. return;
  55402. }
  55403. var bufferWidth = img.width;
  55404. var bufferHeight = img.height;
  55405. canvas.width = bufferWidth;
  55406. canvas.height = bufferHeight;
  55407. context.drawImage(img, 0, 0);
  55408. // Create VertexData from map data
  55409. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55410. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55411. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55412. width: width, height: height,
  55413. subdivisions: subdivisions,
  55414. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55415. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55416. });
  55417. vertexData.applyToMesh(ground, updatable);
  55418. ground._setReady(true);
  55419. //execute ready callback, if set
  55420. if (onReady) {
  55421. onReady(ground);
  55422. }
  55423. };
  55424. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55425. return ground;
  55426. };
  55427. /**
  55428. * Creates a polygon mesh.
  55429. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55430. * 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.
  55431. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55433. * 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).
  55434. * Remember you can only change the shape positions, not their number when updating a polygon.
  55435. */
  55436. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55437. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55438. var shape = options.shape;
  55439. var holes = options.holes || [];
  55440. var depth = options.depth || 0;
  55441. var contours = [];
  55442. var hole = [];
  55443. for (var i = 0; i < shape.length; i++) {
  55444. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55445. }
  55446. var epsilon = 0.00000001;
  55447. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55448. contours.pop();
  55449. }
  55450. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55451. for (var hNb = 0; hNb < holes.length; hNb++) {
  55452. hole = [];
  55453. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55454. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55455. }
  55456. polygonTriangulation.addHole(hole);
  55457. }
  55458. var polygon = polygonTriangulation.build(options.updatable, depth);
  55459. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55460. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55461. vertexData.applyToMesh(polygon, options.updatable);
  55462. return polygon;
  55463. };
  55464. ;
  55465. /**
  55466. * Creates an extruded polygon mesh, with depth in the Y direction.
  55467. * 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).
  55468. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55469. */
  55470. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55471. return MeshBuilder.CreatePolygon(name, options, scene);
  55472. };
  55473. ;
  55474. /**
  55475. * Creates a tube mesh.
  55476. * 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.
  55477. *
  55478. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55479. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55480. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55481. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55482. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55483. * 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.
  55484. * It must return a radius value (positive float) :
  55485. * ```javascript
  55486. * var radiusFunction = function(i, distance) {
  55487. * // do things
  55488. * return radius; }
  55489. * ```
  55490. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55491. * 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
  55492. * 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
  55493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55494. * 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).
  55495. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55496. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55498. */
  55499. MeshBuilder.CreateTube = function (name, options, scene) {
  55500. var path = options.path;
  55501. var instance = options.instance;
  55502. var radius = 1.0;
  55503. if (instance) {
  55504. radius = instance.radius;
  55505. }
  55506. if (options.radius !== undefined) {
  55507. radius = options.radius;
  55508. }
  55509. ;
  55510. var tessellation = options.tessellation || 64 | 0;
  55511. var radiusFunction = options.radiusFunction || null;
  55512. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55513. var invertUV = options.invertUV || false;
  55514. var updatable = options.updatable;
  55515. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55516. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55517. // tube geometry
  55518. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55519. var tangents = path3D.getTangents();
  55520. var normals = path3D.getNormals();
  55521. var distances = path3D.getDistances();
  55522. var pi2 = Math.PI * 2;
  55523. var step = pi2 / tessellation * arc;
  55524. var returnRadius = function () { return radius; };
  55525. var radiusFunctionFinal = radiusFunction || returnRadius;
  55526. var circlePath;
  55527. var rad;
  55528. var normal;
  55529. var rotated;
  55530. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55531. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55532. for (var i = 0; i < path.length; i++) {
  55533. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55534. circlePath = Array(); // current circle array
  55535. normal = normals[i]; // current normal
  55536. for (var t = 0; t < tessellation; t++) {
  55537. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55538. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55539. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55540. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55541. circlePath[t] = rotated;
  55542. }
  55543. circlePaths[index] = circlePath;
  55544. index++;
  55545. }
  55546. // cap
  55547. var capPath = function (nbPoints, pathIndex) {
  55548. var pointCap = Array();
  55549. for (var i = 0; i < nbPoints; i++) {
  55550. pointCap.push(path[pathIndex]);
  55551. }
  55552. return pointCap;
  55553. };
  55554. switch (cap) {
  55555. case BABYLON.Mesh.NO_CAP:
  55556. break;
  55557. case BABYLON.Mesh.CAP_START:
  55558. circlePaths[0] = capPath(tessellation, 0);
  55559. circlePaths[1] = circlePaths[2].slice(0);
  55560. break;
  55561. case BABYLON.Mesh.CAP_END:
  55562. circlePaths[index] = circlePaths[index - 1].slice(0);
  55563. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55564. break;
  55565. case BABYLON.Mesh.CAP_ALL:
  55566. circlePaths[0] = capPath(tessellation, 0);
  55567. circlePaths[1] = circlePaths[2].slice(0);
  55568. circlePaths[index] = circlePaths[index - 1].slice(0);
  55569. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55570. break;
  55571. default:
  55572. break;
  55573. }
  55574. return circlePaths;
  55575. };
  55576. var path3D;
  55577. var pathArray;
  55578. if (instance) {
  55579. var arc = options.arc || instance.arc;
  55580. path3D = (instance.path3D).update(path);
  55581. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55582. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55583. instance.path3D = path3D;
  55584. instance.pathArray = pathArray;
  55585. instance.arc = arc;
  55586. instance.radius = radius;
  55587. return instance;
  55588. }
  55589. // tube creation
  55590. path3D = new BABYLON.Path3D(path);
  55591. var newPathArray = new Array();
  55592. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55593. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55594. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55595. tube.pathArray = pathArray;
  55596. tube.path3D = path3D;
  55597. tube.tessellation = tessellation;
  55598. tube.cap = cap;
  55599. tube.arc = options.arc;
  55600. tube.radius = radius;
  55601. return tube;
  55602. };
  55603. /**
  55604. * Creates a polyhedron mesh.
  55605. *
  55606. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55607. * 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
  55608. * to choose the wanted type.
  55609. * The parameter `size` (positive float, default 1) sets the polygon size.
  55610. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55611. * 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`.
  55612. * 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
  55613. * 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)`).
  55614. * 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
  55615. * 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.
  55616. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55617. * 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).
  55618. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55620. */
  55621. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55622. var polyhedron = new BABYLON.Mesh(name, scene);
  55623. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55624. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55625. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55626. vertexData.applyToMesh(polyhedron, options.updatable);
  55627. return polyhedron;
  55628. };
  55629. /**
  55630. * Creates a decal mesh.
  55631. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55632. * 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.
  55633. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55634. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55635. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55636. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55637. */
  55638. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55639. var indices = sourceMesh.getIndices();
  55640. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55641. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55642. var position = options.position || BABYLON.Vector3.Zero();
  55643. var normal = options.normal || BABYLON.Vector3.Up();
  55644. var size = options.size || BABYLON.Vector3.One();
  55645. var angle = options.angle || 0;
  55646. // Getting correct rotation
  55647. if (!normal) {
  55648. var target = new BABYLON.Vector3(0, 0, 1);
  55649. var camera = sourceMesh.getScene().activeCamera;
  55650. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55651. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55652. }
  55653. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55654. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55655. var pitch = Math.atan2(normal.y, len);
  55656. // Matrix
  55657. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55658. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55659. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55660. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55661. var vertexData = new BABYLON.VertexData();
  55662. vertexData.indices = [];
  55663. vertexData.positions = [];
  55664. vertexData.normals = [];
  55665. vertexData.uvs = [];
  55666. var currentVertexDataIndex = 0;
  55667. var extractDecalVector3 = function (indexId) {
  55668. var result = new BABYLON.PositionNormalVertex();
  55669. if (!indices || !positions || !normals) {
  55670. return result;
  55671. }
  55672. var vertexId = indices[indexId];
  55673. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55674. // Send vector to decal local world
  55675. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55676. // Get normal
  55677. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55678. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55679. return result;
  55680. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55681. var clip = function (vertices, axis) {
  55682. if (vertices.length === 0) {
  55683. return vertices;
  55684. }
  55685. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55686. var clipVertices = function (v0, v1) {
  55687. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55688. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55689. };
  55690. var result = new Array();
  55691. for (var index = 0; index < vertices.length; index += 3) {
  55692. var v1Out;
  55693. var v2Out;
  55694. var v3Out;
  55695. var total = 0;
  55696. var nV1 = null;
  55697. var nV2 = null;
  55698. var nV3 = null;
  55699. var nV4 = null;
  55700. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55701. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55702. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55703. v1Out = d1 > 0;
  55704. v2Out = d2 > 0;
  55705. v3Out = d3 > 0;
  55706. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55707. switch (total) {
  55708. case 0:
  55709. result.push(vertices[index]);
  55710. result.push(vertices[index + 1]);
  55711. result.push(vertices[index + 2]);
  55712. break;
  55713. case 1:
  55714. if (v1Out) {
  55715. nV1 = vertices[index + 1];
  55716. nV2 = vertices[index + 2];
  55717. nV3 = clipVertices(vertices[index], nV1);
  55718. nV4 = clipVertices(vertices[index], nV2);
  55719. }
  55720. if (v2Out) {
  55721. nV1 = vertices[index];
  55722. nV2 = vertices[index + 2];
  55723. nV3 = clipVertices(vertices[index + 1], nV1);
  55724. nV4 = clipVertices(vertices[index + 1], nV2);
  55725. result.push(nV3);
  55726. result.push(nV2.clone());
  55727. result.push(nV1.clone());
  55728. result.push(nV2.clone());
  55729. result.push(nV3.clone());
  55730. result.push(nV4);
  55731. break;
  55732. }
  55733. if (v3Out) {
  55734. nV1 = vertices[index];
  55735. nV2 = vertices[index + 1];
  55736. nV3 = clipVertices(vertices[index + 2], nV1);
  55737. nV4 = clipVertices(vertices[index + 2], nV2);
  55738. }
  55739. if (nV1 && nV2 && nV3 && nV4) {
  55740. result.push(nV1.clone());
  55741. result.push(nV2.clone());
  55742. result.push(nV3);
  55743. result.push(nV4);
  55744. result.push(nV3.clone());
  55745. result.push(nV2.clone());
  55746. }
  55747. break;
  55748. case 2:
  55749. if (!v1Out) {
  55750. nV1 = vertices[index].clone();
  55751. nV2 = clipVertices(nV1, vertices[index + 1]);
  55752. nV3 = clipVertices(nV1, vertices[index + 2]);
  55753. result.push(nV1);
  55754. result.push(nV2);
  55755. result.push(nV3);
  55756. }
  55757. if (!v2Out) {
  55758. nV1 = vertices[index + 1].clone();
  55759. nV2 = clipVertices(nV1, vertices[index + 2]);
  55760. nV3 = clipVertices(nV1, vertices[index]);
  55761. result.push(nV1);
  55762. result.push(nV2);
  55763. result.push(nV3);
  55764. }
  55765. if (!v3Out) {
  55766. nV1 = vertices[index + 2].clone();
  55767. nV2 = clipVertices(nV1, vertices[index]);
  55768. nV3 = clipVertices(nV1, vertices[index + 1]);
  55769. result.push(nV1);
  55770. result.push(nV2);
  55771. result.push(nV3);
  55772. }
  55773. break;
  55774. case 3:
  55775. break;
  55776. }
  55777. }
  55778. return result;
  55779. };
  55780. for (var index = 0; index < indices.length; index += 3) {
  55781. var faceVertices = new Array();
  55782. faceVertices.push(extractDecalVector3(index));
  55783. faceVertices.push(extractDecalVector3(index + 1));
  55784. faceVertices.push(extractDecalVector3(index + 2));
  55785. // Clip
  55786. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55787. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55788. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55789. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55790. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55791. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55792. if (faceVertices.length === 0) {
  55793. continue;
  55794. }
  55795. // Add UVs and get back to world
  55796. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55797. var vertex = faceVertices[vIndex];
  55798. //TODO check for Int32Array | Uint32Array | Uint16Array
  55799. vertexData.indices.push(currentVertexDataIndex);
  55800. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55801. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55802. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55803. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55804. currentVertexDataIndex++;
  55805. }
  55806. }
  55807. // Return mesh
  55808. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55809. vertexData.applyToMesh(decal);
  55810. decal.position = position.clone();
  55811. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55812. return decal;
  55813. };
  55814. // Privates
  55815. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55816. // extrusion geometry
  55817. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55818. var tangents = path3D.getTangents();
  55819. var normals = path3D.getNormals();
  55820. var binormals = path3D.getBinormals();
  55821. var distances = path3D.getDistances();
  55822. var angle = 0;
  55823. var returnScale = function () { return scale !== null ? scale : 1; };
  55824. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55825. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55826. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55827. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55828. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55829. for (var i = 0; i < curve.length; i++) {
  55830. var shapePath = new Array();
  55831. var angleStep = rotate(i, distances[i]);
  55832. var scaleRatio = scl(i, distances[i]);
  55833. for (var p = 0; p < shape.length; p++) {
  55834. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55835. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55836. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55837. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55838. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55839. shapePath[p] = rotated;
  55840. }
  55841. shapePaths[index] = shapePath;
  55842. angle += angleStep;
  55843. index++;
  55844. }
  55845. // cap
  55846. var capPath = function (shapePath) {
  55847. var pointCap = Array();
  55848. var barycenter = BABYLON.Vector3.Zero();
  55849. var i;
  55850. for (i = 0; i < shapePath.length; i++) {
  55851. barycenter.addInPlace(shapePath[i]);
  55852. }
  55853. barycenter.scaleInPlace(1.0 / shapePath.length);
  55854. for (i = 0; i < shapePath.length; i++) {
  55855. pointCap.push(barycenter);
  55856. }
  55857. return pointCap;
  55858. };
  55859. switch (cap) {
  55860. case BABYLON.Mesh.NO_CAP:
  55861. break;
  55862. case BABYLON.Mesh.CAP_START:
  55863. shapePaths[0] = capPath(shapePaths[2]);
  55864. shapePaths[1] = shapePaths[2];
  55865. break;
  55866. case BABYLON.Mesh.CAP_END:
  55867. shapePaths[index] = shapePaths[index - 1];
  55868. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55869. break;
  55870. case BABYLON.Mesh.CAP_ALL:
  55871. shapePaths[0] = capPath(shapePaths[2]);
  55872. shapePaths[1] = shapePaths[2];
  55873. shapePaths[index] = shapePaths[index - 1];
  55874. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55875. break;
  55876. default:
  55877. break;
  55878. }
  55879. return shapePaths;
  55880. };
  55881. var path3D;
  55882. var pathArray;
  55883. if (instance) {
  55884. path3D = (instance.path3D).update(curve);
  55885. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55886. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55887. return instance;
  55888. }
  55889. // extruded shape creation
  55890. path3D = new BABYLON.Path3D(curve);
  55891. var newShapePaths = new Array();
  55892. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55893. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55894. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55895. extrudedGeneric.pathArray = pathArray;
  55896. extrudedGeneric.path3D = path3D;
  55897. extrudedGeneric.cap = cap;
  55898. return extrudedGeneric;
  55899. };
  55900. return MeshBuilder;
  55901. }());
  55902. BABYLON.MeshBuilder = MeshBuilder;
  55903. })(BABYLON || (BABYLON = {}));
  55904. //# sourceMappingURL=babylon.meshBuilder.js.map
  55905. var BABYLON;
  55906. (function (BABYLON) {
  55907. /**
  55908. * Draco compression (https://google.github.io/draco/)
  55909. */
  55910. var DracoCompression = /** @class */ (function () {
  55911. /**
  55912. * Constructor
  55913. * @param numWorkers The number of workers for async operations
  55914. */
  55915. function DracoCompression(numWorkers) {
  55916. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  55917. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  55918. if (!workerBlobUrl || !Worker) {
  55919. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  55920. return;
  55921. }
  55922. var workers = new Array(numWorkers);
  55923. for (var i = 0; i < workers.length; i++) {
  55924. var worker = new Worker(workerBlobUrl);
  55925. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  55926. workers[i] = worker;
  55927. }
  55928. this._workerPool = new BABYLON.WorkerPool(workers);
  55929. }
  55930. /**
  55931. * Stop all async operations and release resources.
  55932. */
  55933. DracoCompression.prototype.dispose = function () {
  55934. this._workerPool.dispose();
  55935. delete this._workerPool;
  55936. };
  55937. /**
  55938. * Decode Draco compressed mesh data to vertex data.
  55939. * @param data The array buffer view for the Draco compression data
  55940. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  55941. * @returns A promise that resolves with the decoded vertex data
  55942. */
  55943. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  55944. var _this = this;
  55945. return new Promise(function (resolve, reject) {
  55946. _this._workerPool.push(function (worker, onComplete) {
  55947. var vertexData = new BABYLON.VertexData();
  55948. var onError = function (error) {
  55949. worker.removeEventListener("error", onError);
  55950. worker.removeEventListener("message", onMessage);
  55951. reject(error);
  55952. onComplete();
  55953. };
  55954. var onMessage = function (message) {
  55955. if (message.data === "done") {
  55956. worker.removeEventListener("error", onError);
  55957. worker.removeEventListener("message", onMessage);
  55958. resolve(vertexData);
  55959. onComplete();
  55960. }
  55961. else if (message.data.id === "indices") {
  55962. vertexData.indices = message.data.value;
  55963. }
  55964. else {
  55965. vertexData.set(message.data.value, message.data.id);
  55966. }
  55967. };
  55968. worker.addEventListener("error", onError);
  55969. worker.addEventListener("message", onMessage);
  55970. var dataCopy = new Uint8Array(data.byteLength);
  55971. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  55972. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  55973. });
  55974. });
  55975. };
  55976. /**
  55977. * The worker function that gets converted to a blob url to pass into a worker.
  55978. */
  55979. DracoCompression._Worker = function () {
  55980. // self is actually a DedicatedWorkerGlobalScope
  55981. var _self = self;
  55982. var decodeMesh = function (data, attributes) {
  55983. var dracoModule = new DracoDecoderModule();
  55984. var buffer = new dracoModule.DecoderBuffer();
  55985. buffer.Init(data, data.byteLength);
  55986. var decoder = new dracoModule.Decoder();
  55987. var geometry;
  55988. var status;
  55989. try {
  55990. var type = decoder.GetEncodedGeometryType(buffer);
  55991. switch (type) {
  55992. case dracoModule.TRIANGULAR_MESH:
  55993. geometry = new dracoModule.Mesh();
  55994. status = decoder.DecodeBufferToMesh(buffer, geometry);
  55995. break;
  55996. case dracoModule.POINT_CLOUD:
  55997. geometry = new dracoModule.PointCloud();
  55998. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  55999. break;
  56000. default:
  56001. throw new Error("Invalid geometry type " + type);
  56002. }
  56003. if (!status.ok() || !geometry.ptr) {
  56004. throw new Error(status.error_msg());
  56005. }
  56006. var numPoints = geometry.num_points();
  56007. if (type === dracoModule.TRIANGULAR_MESH) {
  56008. var numFaces = geometry.num_faces();
  56009. var faceIndices = new dracoModule.DracoInt32Array();
  56010. try {
  56011. var indices = new Uint32Array(numFaces * 3);
  56012. for (var i = 0; i < numFaces; i++) {
  56013. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56014. var offset = i * 3;
  56015. indices[offset + 0] = faceIndices.GetValue(0);
  56016. indices[offset + 1] = faceIndices.GetValue(1);
  56017. indices[offset + 2] = faceIndices.GetValue(2);
  56018. }
  56019. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56020. }
  56021. finally {
  56022. dracoModule.destroy(faceIndices);
  56023. }
  56024. }
  56025. for (var kind in attributes) {
  56026. var uniqueId = attributes[kind];
  56027. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56028. var dracoData = new dracoModule.DracoFloat32Array();
  56029. try {
  56030. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56031. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56032. for (var i = 0; i < babylonData.length; i++) {
  56033. babylonData[i] = dracoData.GetValue(i);
  56034. }
  56035. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56036. }
  56037. finally {
  56038. dracoModule.destroy(dracoData);
  56039. }
  56040. }
  56041. }
  56042. finally {
  56043. if (geometry) {
  56044. dracoModule.destroy(geometry);
  56045. }
  56046. dracoModule.destroy(decoder);
  56047. dracoModule.destroy(buffer);
  56048. }
  56049. _self.postMessage("done");
  56050. };
  56051. _self.onmessage = function (event) {
  56052. switch (event.data.id) {
  56053. case "initDecoder": {
  56054. importScripts(event.data.url);
  56055. break;
  56056. }
  56057. case "decodeMesh": {
  56058. decodeMesh(event.data.data, event.data.attributes);
  56059. break;
  56060. }
  56061. }
  56062. };
  56063. };
  56064. DracoCompression._GetDefaultDecoderUrl = function () {
  56065. if (!BABYLON.Tools.IsWindowObjectExist) {
  56066. return null;
  56067. }
  56068. for (var i = 0; i < document.scripts.length; i++) {
  56069. if (document.scripts[i].type === "text/x-draco-decoder") {
  56070. return document.scripts[i].src;
  56071. }
  56072. }
  56073. return null;
  56074. };
  56075. /**
  56076. * Gets the url to the draco decoder if available.
  56077. */
  56078. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56079. return DracoCompression;
  56080. }());
  56081. BABYLON.DracoCompression = DracoCompression;
  56082. })(BABYLON || (BABYLON = {}));
  56083. //# sourceMappingURL=babylon.dracoCompression.js.map
  56084. var BABYLON;
  56085. (function (BABYLON) {
  56086. var AudioEngine = /** @class */ (function () {
  56087. function AudioEngine() {
  56088. this._audioContext = null;
  56089. this._audioContextInitialized = false;
  56090. this.canUseWebAudio = false;
  56091. this.WarnedWebAudioUnsupported = false;
  56092. this.unlocked = false;
  56093. this.isMP3supported = false;
  56094. this.isOGGsupported = false;
  56095. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56096. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56097. this.canUseWebAudio = true;
  56098. }
  56099. var audioElem = document.createElement('audio');
  56100. try {
  56101. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56102. this.isMP3supported = true;
  56103. }
  56104. }
  56105. catch (e) {
  56106. // protect error during capability check.
  56107. }
  56108. try {
  56109. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56110. this.isOGGsupported = true;
  56111. }
  56112. }
  56113. catch (e) {
  56114. // protect error during capability check.
  56115. }
  56116. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56117. this._unlockiOSaudio();
  56118. }
  56119. else {
  56120. this.unlocked = true;
  56121. }
  56122. }
  56123. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56124. get: function () {
  56125. if (!this._audioContextInitialized) {
  56126. this._initializeAudioContext();
  56127. }
  56128. return this._audioContext;
  56129. },
  56130. enumerable: true,
  56131. configurable: true
  56132. });
  56133. AudioEngine.prototype._unlockiOSaudio = function () {
  56134. var _this = this;
  56135. var unlockaudio = function () {
  56136. if (!_this.audioContext) {
  56137. return;
  56138. }
  56139. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56140. var source = _this.audioContext.createBufferSource();
  56141. source.buffer = buffer;
  56142. source.connect(_this.audioContext.destination);
  56143. source.start(0);
  56144. setTimeout(function () {
  56145. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56146. _this.unlocked = true;
  56147. window.removeEventListener('touchend', unlockaudio, false);
  56148. if (_this.onAudioUnlocked) {
  56149. _this.onAudioUnlocked();
  56150. }
  56151. }
  56152. }, 0);
  56153. };
  56154. window.addEventListener('touchend', unlockaudio, false);
  56155. };
  56156. AudioEngine.prototype._initializeAudioContext = function () {
  56157. try {
  56158. if (this.canUseWebAudio) {
  56159. this._audioContext = new AudioContext();
  56160. // create a global volume gain node
  56161. this.masterGain = this._audioContext.createGain();
  56162. this.masterGain.gain.value = 1;
  56163. this.masterGain.connect(this._audioContext.destination);
  56164. this._audioContextInitialized = true;
  56165. }
  56166. }
  56167. catch (e) {
  56168. this.canUseWebAudio = false;
  56169. BABYLON.Tools.Error("Web Audio: " + e.message);
  56170. }
  56171. };
  56172. AudioEngine.prototype.dispose = function () {
  56173. if (this.canUseWebAudio && this._audioContextInitialized) {
  56174. if (this._connectedAnalyser && this._audioContext) {
  56175. this._connectedAnalyser.stopDebugCanvas();
  56176. this._connectedAnalyser.dispose();
  56177. this.masterGain.disconnect();
  56178. this.masterGain.connect(this._audioContext.destination);
  56179. this._connectedAnalyser = null;
  56180. }
  56181. this.masterGain.gain.value = 1;
  56182. }
  56183. this.WarnedWebAudioUnsupported = false;
  56184. };
  56185. AudioEngine.prototype.getGlobalVolume = function () {
  56186. if (this.canUseWebAudio && this._audioContextInitialized) {
  56187. return this.masterGain.gain.value;
  56188. }
  56189. else {
  56190. return -1;
  56191. }
  56192. };
  56193. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56194. if (this.canUseWebAudio && this._audioContextInitialized) {
  56195. this.masterGain.gain.value = newVolume;
  56196. }
  56197. };
  56198. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56199. if (this._connectedAnalyser) {
  56200. this._connectedAnalyser.stopDebugCanvas();
  56201. }
  56202. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56203. this._connectedAnalyser = analyser;
  56204. this.masterGain.disconnect();
  56205. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56206. }
  56207. };
  56208. return AudioEngine;
  56209. }());
  56210. BABYLON.AudioEngine = AudioEngine;
  56211. })(BABYLON || (BABYLON = {}));
  56212. //# sourceMappingURL=babylon.audioEngine.js.map
  56213. var BABYLON;
  56214. (function (BABYLON) {
  56215. var Sound = /** @class */ (function () {
  56216. /**
  56217. * Create a sound and attach it to a scene
  56218. * @param name Name of your sound
  56219. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56220. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56221. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56222. */
  56223. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56224. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56225. var _this = this;
  56226. this.autoplay = false;
  56227. this.loop = false;
  56228. this.useCustomAttenuation = false;
  56229. this.spatialSound = false;
  56230. this.refDistance = 1;
  56231. this.rolloffFactor = 1;
  56232. this.maxDistance = 100;
  56233. this.distanceModel = "linear";
  56234. this._panningModel = "equalpower";
  56235. this._playbackRate = 1;
  56236. this._streaming = false;
  56237. this._startTime = 0;
  56238. this._startOffset = 0;
  56239. this._position = BABYLON.Vector3.Zero();
  56240. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56241. this._volume = 1;
  56242. this._isReadyToPlay = false;
  56243. this.isPlaying = false;
  56244. this.isPaused = false;
  56245. this._isDirectional = false;
  56246. // Used if you'd like to create a directional sound.
  56247. // If not set, the sound will be omnidirectional
  56248. this._coneInnerAngle = 360;
  56249. this._coneOuterAngle = 360;
  56250. this._coneOuterGain = 0;
  56251. this._isOutputConnected = false;
  56252. this._urlType = "Unknown";
  56253. this.name = name;
  56254. this._scene = scene;
  56255. this._readyToPlayCallback = readyToPlayCallback;
  56256. // Default custom attenuation function is a linear attenuation
  56257. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56258. if (currentDistance < maxDistance) {
  56259. return currentVolume * (1 - currentDistance / maxDistance);
  56260. }
  56261. else {
  56262. return 0;
  56263. }
  56264. };
  56265. if (options) {
  56266. this.autoplay = options.autoplay || false;
  56267. this.loop = options.loop || false;
  56268. // if volume === 0, we need another way to check this option
  56269. if (options.volume !== undefined) {
  56270. this._volume = options.volume;
  56271. }
  56272. this.spatialSound = options.spatialSound || false;
  56273. this.maxDistance = options.maxDistance || 100;
  56274. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56275. this.rolloffFactor = options.rolloffFactor || 1;
  56276. this.refDistance = options.refDistance || 1;
  56277. this.distanceModel = options.distanceModel || "linear";
  56278. this._playbackRate = options.playbackRate || 1;
  56279. this._streaming = options.streaming || false;
  56280. }
  56281. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56282. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56283. this._soundGain.gain.value = this._volume;
  56284. this._inputAudioNode = this._soundGain;
  56285. this._ouputAudioNode = this._soundGain;
  56286. if (this.spatialSound) {
  56287. this._createSpatialParameters();
  56288. }
  56289. this._scene.mainSoundTrack.AddSound(this);
  56290. var validParameter = true;
  56291. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56292. if (urlOrArrayBuffer) {
  56293. if (typeof (urlOrArrayBuffer) === "string")
  56294. this._urlType = "String";
  56295. if (Array.isArray(urlOrArrayBuffer))
  56296. this._urlType = "Array";
  56297. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56298. this._urlType = "ArrayBuffer";
  56299. var urls = [];
  56300. var codecSupportedFound = false;
  56301. switch (this._urlType) {
  56302. case "ArrayBuffer":
  56303. if (urlOrArrayBuffer.byteLength > 0) {
  56304. codecSupportedFound = true;
  56305. this._soundLoaded(urlOrArrayBuffer);
  56306. }
  56307. break;
  56308. case "String":
  56309. urls.push(urlOrArrayBuffer);
  56310. case "Array":
  56311. if (urls.length === 0)
  56312. urls = urlOrArrayBuffer;
  56313. // If we found a supported format, we load it immediately and stop the loop
  56314. for (var i = 0; i < urls.length; i++) {
  56315. var url = urls[i];
  56316. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56317. codecSupportedFound = true;
  56318. }
  56319. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56320. codecSupportedFound = true;
  56321. }
  56322. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56323. codecSupportedFound = true;
  56324. }
  56325. if (url.indexOf("blob:") !== -1) {
  56326. codecSupportedFound = true;
  56327. }
  56328. if (codecSupportedFound) {
  56329. // Loading sound using XHR2
  56330. if (!this._streaming) {
  56331. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56332. }
  56333. else {
  56334. this._htmlAudioElement = new Audio(url);
  56335. this._htmlAudioElement.controls = false;
  56336. this._htmlAudioElement.loop = this.loop;
  56337. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56338. this._htmlAudioElement.preload = "auto";
  56339. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56340. _this._isReadyToPlay = true;
  56341. if (_this.autoplay) {
  56342. _this.play();
  56343. }
  56344. if (_this._readyToPlayCallback) {
  56345. _this._readyToPlayCallback();
  56346. }
  56347. });
  56348. document.body.appendChild(this._htmlAudioElement);
  56349. }
  56350. break;
  56351. }
  56352. }
  56353. break;
  56354. default:
  56355. validParameter = false;
  56356. break;
  56357. }
  56358. if (!validParameter) {
  56359. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56360. }
  56361. else {
  56362. if (!codecSupportedFound) {
  56363. this._isReadyToPlay = true;
  56364. // Simulating a ready to play event to avoid breaking code path
  56365. if (this._readyToPlayCallback) {
  56366. window.setTimeout(function () {
  56367. if (_this._readyToPlayCallback) {
  56368. _this._readyToPlayCallback();
  56369. }
  56370. }, 1000);
  56371. }
  56372. }
  56373. }
  56374. }
  56375. }
  56376. else {
  56377. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56378. this._scene.mainSoundTrack.AddSound(this);
  56379. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56380. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56381. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56382. }
  56383. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56384. if (this._readyToPlayCallback) {
  56385. window.setTimeout(function () {
  56386. if (_this._readyToPlayCallback) {
  56387. _this._readyToPlayCallback();
  56388. }
  56389. }, 1000);
  56390. }
  56391. }
  56392. }
  56393. Sound.prototype.dispose = function () {
  56394. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56395. if (this.isPlaying) {
  56396. this.stop();
  56397. }
  56398. this._isReadyToPlay = false;
  56399. if (this.soundTrackId === -1) {
  56400. this._scene.mainSoundTrack.RemoveSound(this);
  56401. }
  56402. else {
  56403. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56404. }
  56405. if (this._soundGain) {
  56406. this._soundGain.disconnect();
  56407. this._soundGain = null;
  56408. }
  56409. if (this._soundPanner) {
  56410. this._soundPanner.disconnect();
  56411. this._soundPanner = null;
  56412. }
  56413. if (this._soundSource) {
  56414. this._soundSource.disconnect();
  56415. this._soundSource = null;
  56416. }
  56417. this._audioBuffer = null;
  56418. if (this._htmlAudioElement) {
  56419. this._htmlAudioElement.pause();
  56420. this._htmlAudioElement.src = "";
  56421. document.body.removeChild(this._htmlAudioElement);
  56422. }
  56423. if (this._connectedMesh && this._registerFunc) {
  56424. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56425. this._connectedMesh = null;
  56426. }
  56427. }
  56428. };
  56429. Sound.prototype.isReady = function () {
  56430. return this._isReadyToPlay;
  56431. };
  56432. Sound.prototype._soundLoaded = function (audioData) {
  56433. var _this = this;
  56434. if (!BABYLON.Engine.audioEngine.audioContext) {
  56435. return;
  56436. }
  56437. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56438. _this._audioBuffer = buffer;
  56439. _this._isReadyToPlay = true;
  56440. if (_this.autoplay) {
  56441. _this.play();
  56442. }
  56443. if (_this._readyToPlayCallback) {
  56444. _this._readyToPlayCallback();
  56445. }
  56446. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56447. };
  56448. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56449. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56450. this._audioBuffer = audioBuffer;
  56451. this._isReadyToPlay = true;
  56452. }
  56453. };
  56454. Sound.prototype.updateOptions = function (options) {
  56455. if (options) {
  56456. this.loop = options.loop || this.loop;
  56457. this.maxDistance = options.maxDistance || this.maxDistance;
  56458. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56459. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56460. this.refDistance = options.refDistance || this.refDistance;
  56461. this.distanceModel = options.distanceModel || this.distanceModel;
  56462. this._playbackRate = options.playbackRate || this._playbackRate;
  56463. this._updateSpatialParameters();
  56464. if (this.isPlaying) {
  56465. if (this._streaming) {
  56466. this._htmlAudioElement.playbackRate = this._playbackRate;
  56467. }
  56468. else {
  56469. if (this._soundSource) {
  56470. this._soundSource.playbackRate.value = this._playbackRate;
  56471. }
  56472. }
  56473. }
  56474. }
  56475. };
  56476. Sound.prototype._createSpatialParameters = function () {
  56477. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56478. if (this._scene.headphone) {
  56479. this._panningModel = "HRTF";
  56480. }
  56481. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56482. this._updateSpatialParameters();
  56483. this._soundPanner.connect(this._ouputAudioNode);
  56484. this._inputAudioNode = this._soundPanner;
  56485. }
  56486. };
  56487. Sound.prototype._updateSpatialParameters = function () {
  56488. if (this.spatialSound && this._soundPanner) {
  56489. if (this.useCustomAttenuation) {
  56490. // Tricks to disable in a way embedded Web Audio attenuation
  56491. this._soundPanner.distanceModel = "linear";
  56492. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56493. this._soundPanner.refDistance = 1;
  56494. this._soundPanner.rolloffFactor = 1;
  56495. this._soundPanner.panningModel = this._panningModel;
  56496. }
  56497. else {
  56498. this._soundPanner.distanceModel = this.distanceModel;
  56499. this._soundPanner.maxDistance = this.maxDistance;
  56500. this._soundPanner.refDistance = this.refDistance;
  56501. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56502. this._soundPanner.panningModel = this._panningModel;
  56503. }
  56504. }
  56505. };
  56506. Sound.prototype.switchPanningModelToHRTF = function () {
  56507. this._panningModel = "HRTF";
  56508. this._switchPanningModel();
  56509. };
  56510. Sound.prototype.switchPanningModelToEqualPower = function () {
  56511. this._panningModel = "equalpower";
  56512. this._switchPanningModel();
  56513. };
  56514. Sound.prototype._switchPanningModel = function () {
  56515. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56516. this._soundPanner.panningModel = this._panningModel;
  56517. }
  56518. };
  56519. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56520. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56521. if (this._isOutputConnected) {
  56522. this._ouputAudioNode.disconnect();
  56523. }
  56524. this._ouputAudioNode.connect(soundTrackAudioNode);
  56525. this._isOutputConnected = true;
  56526. }
  56527. };
  56528. /**
  56529. * Transform this sound into a directional source
  56530. * @param coneInnerAngle Size of the inner cone in degree
  56531. * @param coneOuterAngle Size of the outer cone in degree
  56532. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56533. */
  56534. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56535. if (coneOuterAngle < coneInnerAngle) {
  56536. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56537. return;
  56538. }
  56539. this._coneInnerAngle = coneInnerAngle;
  56540. this._coneOuterAngle = coneOuterAngle;
  56541. this._coneOuterGain = coneOuterGain;
  56542. this._isDirectional = true;
  56543. if (this.isPlaying && this.loop) {
  56544. this.stop();
  56545. this.play();
  56546. }
  56547. };
  56548. Sound.prototype.setPosition = function (newPosition) {
  56549. this._position = newPosition;
  56550. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56551. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56552. }
  56553. };
  56554. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56555. this._localDirection = newLocalDirection;
  56556. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56557. this._updateDirection();
  56558. }
  56559. };
  56560. Sound.prototype._updateDirection = function () {
  56561. if (!this._connectedMesh || !this._soundPanner) {
  56562. return;
  56563. }
  56564. var mat = this._connectedMesh.getWorldMatrix();
  56565. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56566. direction.normalize();
  56567. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56568. };
  56569. Sound.prototype.updateDistanceFromListener = function () {
  56570. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56571. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56572. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56573. }
  56574. };
  56575. Sound.prototype.setAttenuationFunction = function (callback) {
  56576. this._customAttenuationFunction = callback;
  56577. };
  56578. /**
  56579. * Play the sound
  56580. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56581. * @param offset (optional) Start the sound setting it at a specific time
  56582. */
  56583. Sound.prototype.play = function (time, offset) {
  56584. var _this = this;
  56585. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56586. try {
  56587. if (this._startOffset < 0) {
  56588. time = -this._startOffset;
  56589. this._startOffset = 0;
  56590. }
  56591. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56592. if (!this._soundSource || !this._streamingSource) {
  56593. if (this.spatialSound && this._soundPanner) {
  56594. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56595. if (this._isDirectional) {
  56596. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56597. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56598. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56599. if (this._connectedMesh) {
  56600. this._updateDirection();
  56601. }
  56602. else {
  56603. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56604. }
  56605. }
  56606. }
  56607. }
  56608. if (this._streaming) {
  56609. if (!this._streamingSource) {
  56610. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56611. this._htmlAudioElement.onended = function () { _this._onended(); };
  56612. this._htmlAudioElement.playbackRate = this._playbackRate;
  56613. }
  56614. this._streamingSource.disconnect();
  56615. this._streamingSource.connect(this._inputAudioNode);
  56616. this._htmlAudioElement.play();
  56617. }
  56618. else {
  56619. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56620. this._soundSource.buffer = this._audioBuffer;
  56621. this._soundSource.connect(this._inputAudioNode);
  56622. this._soundSource.loop = this.loop;
  56623. this._soundSource.playbackRate.value = this._playbackRate;
  56624. this._soundSource.onended = function () { _this._onended(); };
  56625. if (this._soundSource.buffer) {
  56626. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56627. }
  56628. }
  56629. this._startTime = startTime;
  56630. this.isPlaying = true;
  56631. this.isPaused = false;
  56632. }
  56633. catch (ex) {
  56634. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56635. }
  56636. }
  56637. };
  56638. Sound.prototype._onended = function () {
  56639. this.isPlaying = false;
  56640. if (this.onended) {
  56641. this.onended();
  56642. }
  56643. };
  56644. /**
  56645. * Stop the sound
  56646. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56647. */
  56648. Sound.prototype.stop = function (time) {
  56649. if (this.isPlaying) {
  56650. if (this._streaming) {
  56651. this._htmlAudioElement.pause();
  56652. // Test needed for Firefox or it will generate an Invalid State Error
  56653. if (this._htmlAudioElement.currentTime > 0) {
  56654. this._htmlAudioElement.currentTime = 0;
  56655. }
  56656. }
  56657. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56658. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56659. this._soundSource.stop(stopTime);
  56660. this._soundSource.onended = function () { };
  56661. if (!this.isPaused) {
  56662. this._startOffset = 0;
  56663. }
  56664. }
  56665. this.isPlaying = false;
  56666. }
  56667. };
  56668. Sound.prototype.pause = function () {
  56669. if (this.isPlaying) {
  56670. this.isPaused = true;
  56671. if (this._streaming) {
  56672. this._htmlAudioElement.pause();
  56673. }
  56674. else if (BABYLON.Engine.audioEngine.audioContext) {
  56675. this.stop(0);
  56676. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56677. }
  56678. }
  56679. };
  56680. Sound.prototype.setVolume = function (newVolume, time) {
  56681. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56682. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56683. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56684. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56685. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56686. }
  56687. else {
  56688. this._soundGain.gain.value = newVolume;
  56689. }
  56690. }
  56691. this._volume = newVolume;
  56692. };
  56693. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56694. this._playbackRate = newPlaybackRate;
  56695. if (this.isPlaying) {
  56696. if (this._streaming) {
  56697. this._htmlAudioElement.playbackRate = this._playbackRate;
  56698. }
  56699. else if (this._soundSource) {
  56700. this._soundSource.playbackRate.value = this._playbackRate;
  56701. }
  56702. }
  56703. };
  56704. Sound.prototype.getVolume = function () {
  56705. return this._volume;
  56706. };
  56707. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56708. var _this = this;
  56709. if (this._connectedMesh && this._registerFunc) {
  56710. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56711. this._registerFunc = null;
  56712. }
  56713. this._connectedMesh = meshToConnectTo;
  56714. if (!this.spatialSound) {
  56715. this.spatialSound = true;
  56716. this._createSpatialParameters();
  56717. if (this.isPlaying && this.loop) {
  56718. this.stop();
  56719. this.play();
  56720. }
  56721. }
  56722. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56723. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56724. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56725. };
  56726. Sound.prototype.detachFromMesh = function () {
  56727. if (this._connectedMesh && this._registerFunc) {
  56728. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56729. this._registerFunc = null;
  56730. this._connectedMesh = null;
  56731. }
  56732. };
  56733. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56734. if (!node.getBoundingInfo) {
  56735. return;
  56736. }
  56737. var mesh = node;
  56738. var boundingInfo = mesh.getBoundingInfo();
  56739. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56740. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56741. this._updateDirection();
  56742. }
  56743. };
  56744. Sound.prototype.clone = function () {
  56745. var _this = this;
  56746. if (!this._streaming) {
  56747. var setBufferAndRun = function () {
  56748. if (_this._isReadyToPlay) {
  56749. clonedSound._audioBuffer = _this.getAudioBuffer();
  56750. clonedSound._isReadyToPlay = true;
  56751. if (clonedSound.autoplay) {
  56752. clonedSound.play();
  56753. }
  56754. }
  56755. else {
  56756. window.setTimeout(setBufferAndRun, 300);
  56757. }
  56758. };
  56759. var currentOptions = {
  56760. autoplay: this.autoplay, loop: this.loop,
  56761. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56762. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56763. refDistance: this.refDistance, distanceModel: this.distanceModel
  56764. };
  56765. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56766. if (this.useCustomAttenuation) {
  56767. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56768. }
  56769. clonedSound.setPosition(this._position);
  56770. clonedSound.setPlaybackRate(this._playbackRate);
  56771. setBufferAndRun();
  56772. return clonedSound;
  56773. }
  56774. else {
  56775. return null;
  56776. }
  56777. };
  56778. Sound.prototype.getAudioBuffer = function () {
  56779. return this._audioBuffer;
  56780. };
  56781. Sound.prototype.serialize = function () {
  56782. var serializationObject = {
  56783. name: this.name,
  56784. url: this.name,
  56785. autoplay: this.autoplay,
  56786. loop: this.loop,
  56787. volume: this._volume,
  56788. spatialSound: this.spatialSound,
  56789. maxDistance: this.maxDistance,
  56790. rolloffFactor: this.rolloffFactor,
  56791. refDistance: this.refDistance,
  56792. distanceModel: this.distanceModel,
  56793. playbackRate: this._playbackRate,
  56794. panningModel: this._panningModel,
  56795. soundTrackId: this.soundTrackId
  56796. };
  56797. if (this.spatialSound) {
  56798. if (this._connectedMesh)
  56799. serializationObject.connectedMeshId = this._connectedMesh.id;
  56800. serializationObject.position = this._position.asArray();
  56801. serializationObject.refDistance = this.refDistance;
  56802. serializationObject.distanceModel = this.distanceModel;
  56803. serializationObject.isDirectional = this._isDirectional;
  56804. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56805. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56806. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56807. serializationObject.coneOuterGain = this._coneOuterGain;
  56808. }
  56809. return serializationObject;
  56810. };
  56811. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56812. var soundName = parsedSound.name;
  56813. var soundUrl;
  56814. if (parsedSound.url) {
  56815. soundUrl = rootUrl + parsedSound.url;
  56816. }
  56817. else {
  56818. soundUrl = rootUrl + soundName;
  56819. }
  56820. var options = {
  56821. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56822. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56823. rolloffFactor: parsedSound.rolloffFactor,
  56824. refDistance: parsedSound.refDistance,
  56825. distanceModel: parsedSound.distanceModel,
  56826. playbackRate: parsedSound.playbackRate
  56827. };
  56828. var newSound;
  56829. if (!sourceSound) {
  56830. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56831. scene._addPendingData(newSound);
  56832. }
  56833. else {
  56834. var setBufferAndRun = function () {
  56835. if (sourceSound._isReadyToPlay) {
  56836. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56837. newSound._isReadyToPlay = true;
  56838. if (newSound.autoplay) {
  56839. newSound.play();
  56840. }
  56841. }
  56842. else {
  56843. window.setTimeout(setBufferAndRun, 300);
  56844. }
  56845. };
  56846. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56847. setBufferAndRun();
  56848. }
  56849. if (parsedSound.position) {
  56850. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56851. newSound.setPosition(soundPosition);
  56852. }
  56853. if (parsedSound.isDirectional) {
  56854. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56855. if (parsedSound.localDirectionToMesh) {
  56856. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56857. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56858. }
  56859. }
  56860. if (parsedSound.connectedMeshId) {
  56861. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56862. if (connectedMesh) {
  56863. newSound.attachToMesh(connectedMesh);
  56864. }
  56865. }
  56866. return newSound;
  56867. };
  56868. return Sound;
  56869. }());
  56870. BABYLON.Sound = Sound;
  56871. })(BABYLON || (BABYLON = {}));
  56872. //# sourceMappingURL=babylon.sound.js.map
  56873. var BABYLON;
  56874. (function (BABYLON) {
  56875. var SoundTrack = /** @class */ (function () {
  56876. function SoundTrack(scene, options) {
  56877. this.id = -1;
  56878. this._isMainTrack = false;
  56879. this._isInitialized = false;
  56880. this._scene = scene;
  56881. this.soundCollection = new Array();
  56882. this._options = options;
  56883. if (!this._isMainTrack) {
  56884. this._scene.soundTracks.push(this);
  56885. this.id = this._scene.soundTracks.length - 1;
  56886. }
  56887. }
  56888. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56889. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56890. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56891. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56892. if (this._options) {
  56893. if (this._options.volume) {
  56894. this._outputAudioNode.gain.value = this._options.volume;
  56895. }
  56896. if (this._options.mainTrack) {
  56897. this._isMainTrack = this._options.mainTrack;
  56898. }
  56899. }
  56900. this._isInitialized = true;
  56901. }
  56902. };
  56903. SoundTrack.prototype.dispose = function () {
  56904. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56905. if (this._connectedAnalyser) {
  56906. this._connectedAnalyser.stopDebugCanvas();
  56907. }
  56908. while (this.soundCollection.length) {
  56909. this.soundCollection[0].dispose();
  56910. }
  56911. if (this._outputAudioNode) {
  56912. this._outputAudioNode.disconnect();
  56913. }
  56914. this._outputAudioNode = null;
  56915. }
  56916. };
  56917. SoundTrack.prototype.AddSound = function (sound) {
  56918. if (!this._isInitialized) {
  56919. this._initializeSoundTrackAudioGraph();
  56920. }
  56921. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56922. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56923. }
  56924. if (sound.soundTrackId) {
  56925. if (sound.soundTrackId === -1) {
  56926. this._scene.mainSoundTrack.RemoveSound(sound);
  56927. }
  56928. else {
  56929. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56930. }
  56931. }
  56932. this.soundCollection.push(sound);
  56933. sound.soundTrackId = this.id;
  56934. };
  56935. SoundTrack.prototype.RemoveSound = function (sound) {
  56936. var index = this.soundCollection.indexOf(sound);
  56937. if (index !== -1) {
  56938. this.soundCollection.splice(index, 1);
  56939. }
  56940. };
  56941. SoundTrack.prototype.setVolume = function (newVolume) {
  56942. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56943. this._outputAudioNode.gain.value = newVolume;
  56944. }
  56945. };
  56946. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56948. for (var i = 0; i < this.soundCollection.length; i++) {
  56949. this.soundCollection[i].switchPanningModelToHRTF();
  56950. }
  56951. }
  56952. };
  56953. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56954. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56955. for (var i = 0; i < this.soundCollection.length; i++) {
  56956. this.soundCollection[i].switchPanningModelToEqualPower();
  56957. }
  56958. }
  56959. };
  56960. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56961. if (this._connectedAnalyser) {
  56962. this._connectedAnalyser.stopDebugCanvas();
  56963. }
  56964. this._connectedAnalyser = analyser;
  56965. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56966. this._outputAudioNode.disconnect();
  56967. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56968. }
  56969. };
  56970. return SoundTrack;
  56971. }());
  56972. BABYLON.SoundTrack = SoundTrack;
  56973. })(BABYLON || (BABYLON = {}));
  56974. //# sourceMappingURL=babylon.soundtrack.js.map
  56975. var BABYLON;
  56976. (function (BABYLON) {
  56977. var Analyser = /** @class */ (function () {
  56978. function Analyser(scene) {
  56979. this.SMOOTHING = 0.75;
  56980. this.FFT_SIZE = 512;
  56981. this.BARGRAPHAMPLITUDE = 256;
  56982. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56983. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56984. this._scene = scene;
  56985. this._audioEngine = BABYLON.Engine.audioEngine;
  56986. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56987. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56988. this._webAudioAnalyser.minDecibels = -140;
  56989. this._webAudioAnalyser.maxDecibels = 0;
  56990. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56991. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56992. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56993. }
  56994. }
  56995. Analyser.prototype.getFrequencyBinCount = function () {
  56996. if (this._audioEngine.canUseWebAudio) {
  56997. return this._webAudioAnalyser.frequencyBinCount;
  56998. }
  56999. else {
  57000. return 0;
  57001. }
  57002. };
  57003. Analyser.prototype.getByteFrequencyData = function () {
  57004. if (this._audioEngine.canUseWebAudio) {
  57005. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57006. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57007. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57008. }
  57009. return this._byteFreqs;
  57010. };
  57011. Analyser.prototype.getByteTimeDomainData = function () {
  57012. if (this._audioEngine.canUseWebAudio) {
  57013. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57014. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57015. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57016. }
  57017. return this._byteTime;
  57018. };
  57019. Analyser.prototype.getFloatFrequencyData = function () {
  57020. if (this._audioEngine.canUseWebAudio) {
  57021. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57022. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57023. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57024. }
  57025. return this._floatFreqs;
  57026. };
  57027. Analyser.prototype.drawDebugCanvas = function () {
  57028. var _this = this;
  57029. if (this._audioEngine.canUseWebAudio) {
  57030. if (!this._debugCanvas) {
  57031. this._debugCanvas = document.createElement("canvas");
  57032. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57033. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57034. this._debugCanvas.style.position = "absolute";
  57035. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57036. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57037. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57038. document.body.appendChild(this._debugCanvas);
  57039. this._registerFunc = function () {
  57040. _this.drawDebugCanvas();
  57041. };
  57042. this._scene.registerBeforeRender(this._registerFunc);
  57043. }
  57044. if (this._registerFunc && this._debugCanvasContext) {
  57045. var workingArray = this.getByteFrequencyData();
  57046. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57047. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57048. // Draw the frequency domain chart.
  57049. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57050. var value = workingArray[i];
  57051. var percent = value / this.BARGRAPHAMPLITUDE;
  57052. var height = this.DEBUGCANVASSIZE.height * percent;
  57053. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57054. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57055. var hue = i / this.getFrequencyBinCount() * 360;
  57056. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57057. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57058. }
  57059. }
  57060. }
  57061. };
  57062. Analyser.prototype.stopDebugCanvas = function () {
  57063. if (this._debugCanvas) {
  57064. if (this._registerFunc) {
  57065. this._scene.unregisterBeforeRender(this._registerFunc);
  57066. this._registerFunc = null;
  57067. }
  57068. document.body.removeChild(this._debugCanvas);
  57069. this._debugCanvas = null;
  57070. this._debugCanvasContext = null;
  57071. }
  57072. };
  57073. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57074. if (this._audioEngine.canUseWebAudio) {
  57075. inputAudioNode.connect(this._webAudioAnalyser);
  57076. this._webAudioAnalyser.connect(outputAudioNode);
  57077. }
  57078. };
  57079. Analyser.prototype.dispose = function () {
  57080. if (this._audioEngine.canUseWebAudio) {
  57081. this._webAudioAnalyser.disconnect();
  57082. }
  57083. };
  57084. return Analyser;
  57085. }());
  57086. BABYLON.Analyser = Analyser;
  57087. })(BABYLON || (BABYLON = {}));
  57088. //# sourceMappingURL=babylon.analyser.js.map
  57089. var BABYLON;
  57090. (function (BABYLON) {
  57091. var CubeTexture = /** @class */ (function (_super) {
  57092. __extends(CubeTexture, _super);
  57093. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57094. if (extensions === void 0) { extensions = null; }
  57095. if (noMipmap === void 0) { noMipmap = false; }
  57096. if (files === void 0) { files = null; }
  57097. if (onLoad === void 0) { onLoad = null; }
  57098. if (onError === void 0) { onError = null; }
  57099. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57100. if (prefiltered === void 0) { prefiltered = false; }
  57101. if (forcedExtension === void 0) { forcedExtension = null; }
  57102. var _this = _super.call(this, scene) || this;
  57103. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57104. /**
  57105. * Gets or sets the center of the bounding box associated with the cube texture
  57106. * It must define where the camera used to render the texture was set
  57107. */
  57108. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57109. _this.name = rootUrl;
  57110. _this.url = rootUrl;
  57111. _this._noMipmap = noMipmap;
  57112. _this.hasAlpha = false;
  57113. _this._format = format;
  57114. _this._prefiltered = prefiltered;
  57115. _this.isCube = true;
  57116. _this._textureMatrix = BABYLON.Matrix.Identity();
  57117. if (prefiltered) {
  57118. _this.gammaSpace = false;
  57119. }
  57120. if (!rootUrl && !files) {
  57121. return _this;
  57122. }
  57123. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57124. var lastDot = rootUrl.lastIndexOf(".");
  57125. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57126. var isDDS = (extension === ".dds");
  57127. if (!files) {
  57128. if (!isDDS && !extensions) {
  57129. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57130. }
  57131. files = [];
  57132. if (extensions) {
  57133. for (var index = 0; index < extensions.length; index++) {
  57134. files.push(rootUrl + extensions[index]);
  57135. }
  57136. }
  57137. }
  57138. _this._files = files;
  57139. if (!_this._texture) {
  57140. if (!scene.useDelayedTextureLoading) {
  57141. if (prefiltered) {
  57142. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57143. }
  57144. else {
  57145. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57146. }
  57147. }
  57148. else {
  57149. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57150. }
  57151. }
  57152. else if (onLoad) {
  57153. if (_this._texture.isReady) {
  57154. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57155. }
  57156. else {
  57157. _this._texture.onLoadedObservable.add(onLoad);
  57158. }
  57159. }
  57160. return _this;
  57161. }
  57162. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57163. get: function () {
  57164. return this._boundingBoxSize;
  57165. },
  57166. /**
  57167. * Gets or sets the size of the bounding box associated with the cube texture
  57168. * When defined, the cubemap will switch to local mode
  57169. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57170. * @example https://www.babylonjs-playground.com/#RNASML
  57171. */
  57172. set: function (value) {
  57173. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57174. return;
  57175. }
  57176. this._boundingBoxSize = value;
  57177. var scene = this.getScene();
  57178. if (scene) {
  57179. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57180. }
  57181. },
  57182. enumerable: true,
  57183. configurable: true
  57184. });
  57185. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57186. var rootUrlKey = "";
  57187. files.forEach(function (url) { return rootUrlKey += url; });
  57188. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57189. };
  57190. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57191. if (forcedExtension === void 0) { forcedExtension = null; }
  57192. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57193. };
  57194. // Methods
  57195. CubeTexture.prototype.delayLoad = function () {
  57196. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57197. return;
  57198. }
  57199. var scene = this.getScene();
  57200. if (!scene) {
  57201. return;
  57202. }
  57203. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57204. this._texture = this._getFromCache(this.url, this._noMipmap);
  57205. if (!this._texture) {
  57206. if (this._prefiltered) {
  57207. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57208. }
  57209. else {
  57210. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57211. }
  57212. }
  57213. };
  57214. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57215. return this._textureMatrix;
  57216. };
  57217. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57218. this._textureMatrix = value;
  57219. };
  57220. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57221. var texture = BABYLON.SerializationHelper.Parse(function () {
  57222. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57223. }, parsedTexture, scene);
  57224. // Local Cubemaps
  57225. if (parsedTexture.boundingBoxPosition) {
  57226. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57227. }
  57228. if (parsedTexture.boundingBoxSize) {
  57229. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57230. }
  57231. // Animations
  57232. if (parsedTexture.animations) {
  57233. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57234. var parsedAnimation = parsedTexture.animations[animationIndex];
  57235. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57236. }
  57237. }
  57238. return texture;
  57239. };
  57240. CubeTexture.prototype.clone = function () {
  57241. var _this = this;
  57242. return BABYLON.SerializationHelper.Clone(function () {
  57243. var scene = _this.getScene();
  57244. if (!scene) {
  57245. return _this;
  57246. }
  57247. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57248. }, this);
  57249. };
  57250. return CubeTexture;
  57251. }(BABYLON.BaseTexture));
  57252. BABYLON.CubeTexture = CubeTexture;
  57253. })(BABYLON || (BABYLON = {}));
  57254. //# sourceMappingURL=babylon.cubeTexture.js.map
  57255. var BABYLON;
  57256. (function (BABYLON) {
  57257. var RenderTargetTexture = /** @class */ (function (_super) {
  57258. __extends(RenderTargetTexture, _super);
  57259. /**
  57260. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57261. * or used a shadow, depth texture...
  57262. * @param name The friendly name of the texture
  57263. * @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)
  57264. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57265. * @param generateMipMaps True if mip maps need to be generated after render.
  57266. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57267. * @param type The type of the buffer in the RTT (int, half float, float...)
  57268. * @param isCube True if a cube texture needs to be created
  57269. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57270. * @param generateDepthBuffer True to generate a depth buffer
  57271. * @param generateStencilBuffer True to generate a stencil buffer
  57272. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57273. */
  57274. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57275. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57276. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57277. if (isCube === void 0) { isCube = false; }
  57278. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57279. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57280. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57281. if (isMulti === void 0) { isMulti = false; }
  57282. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57283. _this.isCube = isCube;
  57284. /**
  57285. * Use this list to define the list of mesh you want to render.
  57286. */
  57287. _this.renderList = new Array();
  57288. _this.renderParticles = true;
  57289. _this.renderSprites = false;
  57290. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57291. _this.ignoreCameraViewport = false;
  57292. // Events
  57293. /**
  57294. * An event triggered when the texture is unbind.
  57295. * @type {BABYLON.Observable}
  57296. */
  57297. _this.onBeforeBindObservable = new BABYLON.Observable();
  57298. /**
  57299. * An event triggered when the texture is unbind.
  57300. * @type {BABYLON.Observable}
  57301. */
  57302. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57303. /**
  57304. * An event triggered before rendering the texture
  57305. * @type {BABYLON.Observable}
  57306. */
  57307. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57308. /**
  57309. * An event triggered after rendering the texture
  57310. * @type {BABYLON.Observable}
  57311. */
  57312. _this.onAfterRenderObservable = new BABYLON.Observable();
  57313. /**
  57314. * An event triggered after the texture clear
  57315. * @type {BABYLON.Observable}
  57316. */
  57317. _this.onClearObservable = new BABYLON.Observable();
  57318. _this._currentRefreshId = -1;
  57319. _this._refreshRate = 1;
  57320. _this._samples = 1;
  57321. /**
  57322. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57323. * It must define where the camera used to render the texture is set
  57324. */
  57325. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57326. scene = _this.getScene();
  57327. if (!scene) {
  57328. return _this;
  57329. }
  57330. _this._engine = scene.getEngine();
  57331. _this.name = name;
  57332. _this.isRenderTarget = true;
  57333. _this._initialSizeParameter = size;
  57334. _this._processSizeParameter(size);
  57335. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57336. });
  57337. _this._generateMipMaps = generateMipMaps ? true : false;
  57338. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57339. // Rendering groups
  57340. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57341. if (isMulti) {
  57342. return _this;
  57343. }
  57344. _this._renderTargetOptions = {
  57345. generateMipMaps: generateMipMaps,
  57346. type: type,
  57347. samplingMode: samplingMode,
  57348. generateDepthBuffer: generateDepthBuffer,
  57349. generateStencilBuffer: generateStencilBuffer
  57350. };
  57351. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57352. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57353. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57354. }
  57355. if (isCube) {
  57356. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57357. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57358. _this._textureMatrix = BABYLON.Matrix.Identity();
  57359. }
  57360. else {
  57361. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57362. }
  57363. return _this;
  57364. }
  57365. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57366. get: function () {
  57367. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57368. },
  57369. enumerable: true,
  57370. configurable: true
  57371. });
  57372. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57373. get: function () {
  57374. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57375. },
  57376. enumerable: true,
  57377. configurable: true
  57378. });
  57379. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57380. get: function () {
  57381. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57382. },
  57383. enumerable: true,
  57384. configurable: true
  57385. });
  57386. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57387. set: function (callback) {
  57388. if (this._onAfterUnbindObserver) {
  57389. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57390. }
  57391. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57392. },
  57393. enumerable: true,
  57394. configurable: true
  57395. });
  57396. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57397. set: function (callback) {
  57398. if (this._onBeforeRenderObserver) {
  57399. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57400. }
  57401. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57402. },
  57403. enumerable: true,
  57404. configurable: true
  57405. });
  57406. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57407. set: function (callback) {
  57408. if (this._onAfterRenderObserver) {
  57409. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57410. }
  57411. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57412. },
  57413. enumerable: true,
  57414. configurable: true
  57415. });
  57416. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57417. set: function (callback) {
  57418. if (this._onClearObserver) {
  57419. this.onClearObservable.remove(this._onClearObserver);
  57420. }
  57421. this._onClearObserver = this.onClearObservable.add(callback);
  57422. },
  57423. enumerable: true,
  57424. configurable: true
  57425. });
  57426. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57427. get: function () {
  57428. return this._renderTargetOptions;
  57429. },
  57430. enumerable: true,
  57431. configurable: true
  57432. });
  57433. RenderTargetTexture.prototype._onRatioRescale = function () {
  57434. if (this._sizeRatio) {
  57435. this.resize(this._initialSizeParameter);
  57436. }
  57437. };
  57438. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57439. get: function () {
  57440. return this._boundingBoxSize;
  57441. },
  57442. /**
  57443. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57444. * When defined, the cubemap will switch to local mode
  57445. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57446. * @example https://www.babylonjs-playground.com/#RNASML
  57447. */
  57448. set: function (value) {
  57449. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57450. return;
  57451. }
  57452. this._boundingBoxSize = value;
  57453. var scene = this.getScene();
  57454. if (scene) {
  57455. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57456. }
  57457. },
  57458. enumerable: true,
  57459. configurable: true
  57460. });
  57461. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57462. if (size.ratio) {
  57463. this._sizeRatio = size.ratio;
  57464. this._size = {
  57465. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57466. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57467. };
  57468. }
  57469. else {
  57470. this._size = size;
  57471. }
  57472. };
  57473. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57474. get: function () {
  57475. return this._samples;
  57476. },
  57477. set: function (value) {
  57478. if (this._samples === value) {
  57479. return;
  57480. }
  57481. var scene = this.getScene();
  57482. if (!scene) {
  57483. return;
  57484. }
  57485. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57486. },
  57487. enumerable: true,
  57488. configurable: true
  57489. });
  57490. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57491. this._currentRefreshId = -1;
  57492. };
  57493. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57494. get: function () {
  57495. return this._refreshRate;
  57496. },
  57497. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57498. set: function (value) {
  57499. this._refreshRate = value;
  57500. this.resetRefreshCounter();
  57501. },
  57502. enumerable: true,
  57503. configurable: true
  57504. });
  57505. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57506. if (!this._postProcessManager) {
  57507. var scene = this.getScene();
  57508. if (!scene) {
  57509. return;
  57510. }
  57511. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57512. this._postProcesses = new Array();
  57513. }
  57514. this._postProcesses.push(postProcess);
  57515. this._postProcesses[0].autoClear = false;
  57516. };
  57517. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57518. if (!this._postProcesses) {
  57519. return;
  57520. }
  57521. if (dispose) {
  57522. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57523. var postProcess = _a[_i];
  57524. postProcess.dispose();
  57525. }
  57526. }
  57527. this._postProcesses = [];
  57528. };
  57529. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57530. if (!this._postProcesses) {
  57531. return;
  57532. }
  57533. var index = this._postProcesses.indexOf(postProcess);
  57534. if (index === -1) {
  57535. return;
  57536. }
  57537. this._postProcesses.splice(index, 1);
  57538. if (this._postProcesses.length > 0) {
  57539. this._postProcesses[0].autoClear = false;
  57540. }
  57541. };
  57542. RenderTargetTexture.prototype._shouldRender = function () {
  57543. if (this._currentRefreshId === -1) {
  57544. this._currentRefreshId = 1;
  57545. return true;
  57546. }
  57547. if (this.refreshRate === this._currentRefreshId) {
  57548. this._currentRefreshId = 1;
  57549. return true;
  57550. }
  57551. this._currentRefreshId++;
  57552. return false;
  57553. };
  57554. RenderTargetTexture.prototype.getRenderSize = function () {
  57555. if (this._size.width) {
  57556. return this._size.width;
  57557. }
  57558. return this._size;
  57559. };
  57560. RenderTargetTexture.prototype.getRenderWidth = function () {
  57561. if (this._size.width) {
  57562. return this._size.width;
  57563. }
  57564. return this._size;
  57565. };
  57566. RenderTargetTexture.prototype.getRenderHeight = function () {
  57567. if (this._size.width) {
  57568. return this._size.height;
  57569. }
  57570. return this._size;
  57571. };
  57572. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57573. get: function () {
  57574. return true;
  57575. },
  57576. enumerable: true,
  57577. configurable: true
  57578. });
  57579. RenderTargetTexture.prototype.scale = function (ratio) {
  57580. var newSize = this.getRenderSize() * ratio;
  57581. this.resize(newSize);
  57582. };
  57583. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57584. if (this.isCube) {
  57585. return this._textureMatrix;
  57586. }
  57587. return _super.prototype.getReflectionTextureMatrix.call(this);
  57588. };
  57589. RenderTargetTexture.prototype.resize = function (size) {
  57590. this.releaseInternalTexture();
  57591. var scene = this.getScene();
  57592. if (!scene) {
  57593. return;
  57594. }
  57595. this._processSizeParameter(size);
  57596. if (this.isCube) {
  57597. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57598. }
  57599. else {
  57600. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57601. }
  57602. };
  57603. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57604. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57605. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57606. var scene = this.getScene();
  57607. if (!scene) {
  57608. return;
  57609. }
  57610. var engine = scene.getEngine();
  57611. if (this.useCameraPostProcesses !== undefined) {
  57612. useCameraPostProcess = this.useCameraPostProcesses;
  57613. }
  57614. if (this._waitingRenderList) {
  57615. this.renderList = [];
  57616. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57617. var id = this._waitingRenderList[index];
  57618. var mesh_1 = scene.getMeshByID(id);
  57619. if (mesh_1) {
  57620. this.renderList.push(mesh_1);
  57621. }
  57622. }
  57623. delete this._waitingRenderList;
  57624. }
  57625. // Is predicate defined?
  57626. if (this.renderListPredicate) {
  57627. if (this.renderList) {
  57628. this.renderList.splice(0); // Clear previous renderList
  57629. }
  57630. else {
  57631. this.renderList = [];
  57632. }
  57633. var scene = this.getScene();
  57634. if (!scene) {
  57635. return;
  57636. }
  57637. var sceneMeshes = scene.meshes;
  57638. for (var index = 0; index < sceneMeshes.length; index++) {
  57639. var mesh = sceneMeshes[index];
  57640. if (this.renderListPredicate(mesh)) {
  57641. this.renderList.push(mesh);
  57642. }
  57643. }
  57644. }
  57645. this.onBeforeBindObservable.notifyObservers(this);
  57646. // Set custom projection.
  57647. // Needs to be before binding to prevent changing the aspect ratio.
  57648. var camera;
  57649. if (this.activeCamera) {
  57650. camera = this.activeCamera;
  57651. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57652. if (this.activeCamera !== scene.activeCamera) {
  57653. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57654. }
  57655. }
  57656. else {
  57657. camera = scene.activeCamera;
  57658. if (camera) {
  57659. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57660. }
  57661. }
  57662. // Prepare renderingManager
  57663. this._renderingManager.reset();
  57664. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57665. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57666. var sceneRenderId = scene.getRenderId();
  57667. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57668. var mesh = currentRenderList[meshIndex];
  57669. if (mesh) {
  57670. if (!mesh.isReady()) {
  57671. // Reset _currentRefreshId
  57672. this.resetRefreshCounter();
  57673. continue;
  57674. }
  57675. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57676. var isMasked = void 0;
  57677. if (!this.renderList && camera) {
  57678. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57679. }
  57680. else {
  57681. isMasked = false;
  57682. }
  57683. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57684. mesh._activate(sceneRenderId);
  57685. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57686. var subMesh = mesh.subMeshes[subIndex];
  57687. scene._activeIndices.addCount(subMesh.indexCount, false);
  57688. this._renderingManager.dispatch(subMesh, mesh);
  57689. }
  57690. }
  57691. }
  57692. }
  57693. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57694. var particleSystem = scene.particleSystems[particleIndex];
  57695. var emitter = particleSystem.emitter;
  57696. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57697. continue;
  57698. }
  57699. if (currentRenderList.indexOf(emitter) >= 0) {
  57700. this._renderingManager.dispatchParticles(particleSystem);
  57701. }
  57702. }
  57703. if (this.isCube) {
  57704. for (var face = 0; face < 6; face++) {
  57705. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57706. scene.incrementRenderId();
  57707. scene.resetCachedMaterial();
  57708. }
  57709. }
  57710. else {
  57711. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57712. }
  57713. this.onAfterUnbindObservable.notifyObservers(this);
  57714. if (scene.activeCamera) {
  57715. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57716. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57717. }
  57718. engine.setViewport(scene.activeCamera.viewport);
  57719. }
  57720. scene.resetCachedMaterial();
  57721. };
  57722. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57723. var minimum = 128;
  57724. var x = renderDimension * scale;
  57725. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57726. // Ensure we don't exceed the render dimension (while staying POT)
  57727. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57728. };
  57729. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57730. var _this = this;
  57731. if (!this._texture) {
  57732. return;
  57733. }
  57734. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57735. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57736. });
  57737. };
  57738. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57739. var scene = this.getScene();
  57740. if (!scene) {
  57741. return;
  57742. }
  57743. var engine = scene.getEngine();
  57744. if (!this._texture) {
  57745. return;
  57746. }
  57747. // Bind
  57748. if (this._postProcessManager) {
  57749. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57750. }
  57751. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57752. if (this._texture) {
  57753. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57754. }
  57755. }
  57756. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57757. // Clear
  57758. if (this.onClearObservable.hasObservers()) {
  57759. this.onClearObservable.notifyObservers(engine);
  57760. }
  57761. else {
  57762. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57763. }
  57764. if (!this._doNotChangeAspectRatio) {
  57765. scene.updateTransformMatrix(true);
  57766. }
  57767. // Render
  57768. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57769. if (this._postProcessManager) {
  57770. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57771. }
  57772. else if (useCameraPostProcess) {
  57773. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57774. }
  57775. if (!this._doNotChangeAspectRatio) {
  57776. scene.updateTransformMatrix(true);
  57777. }
  57778. // Dump ?
  57779. if (dumpForDebug) {
  57780. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57781. }
  57782. // Unbind
  57783. if (!this.isCube || faceIndex === 5) {
  57784. if (this.isCube) {
  57785. if (faceIndex === 5) {
  57786. engine.generateMipMapsForCubemap(this._texture);
  57787. }
  57788. }
  57789. this.unbindFrameBuffer(engine, faceIndex);
  57790. }
  57791. else {
  57792. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57793. }
  57794. };
  57795. /**
  57796. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57797. * This allowed control for front to back rendering or reversly depending of the special needs.
  57798. *
  57799. * @param renderingGroupId The rendering group id corresponding to its index
  57800. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57801. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57802. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57803. */
  57804. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57805. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57806. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57807. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57808. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57809. };
  57810. /**
  57811. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57812. *
  57813. * @param renderingGroupId The rendering group id corresponding to its index
  57814. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57815. */
  57816. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57817. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57818. };
  57819. RenderTargetTexture.prototype.clone = function () {
  57820. var textureSize = this.getSize();
  57821. 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);
  57822. // Base texture
  57823. newTexture.hasAlpha = this.hasAlpha;
  57824. newTexture.level = this.level;
  57825. // RenderTarget Texture
  57826. newTexture.coordinatesMode = this.coordinatesMode;
  57827. if (this.renderList) {
  57828. newTexture.renderList = this.renderList.slice(0);
  57829. }
  57830. return newTexture;
  57831. };
  57832. RenderTargetTexture.prototype.serialize = function () {
  57833. if (!this.name) {
  57834. return null;
  57835. }
  57836. var serializationObject = _super.prototype.serialize.call(this);
  57837. serializationObject.renderTargetSize = this.getRenderSize();
  57838. serializationObject.renderList = [];
  57839. if (this.renderList) {
  57840. for (var index = 0; index < this.renderList.length; index++) {
  57841. serializationObject.renderList.push(this.renderList[index].id);
  57842. }
  57843. }
  57844. return serializationObject;
  57845. };
  57846. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57847. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57848. var objBuffer = this.getInternalTexture();
  57849. var scene = this.getScene();
  57850. if (objBuffer && scene) {
  57851. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57852. }
  57853. };
  57854. RenderTargetTexture.prototype.dispose = function () {
  57855. if (this._postProcessManager) {
  57856. this._postProcessManager.dispose();
  57857. this._postProcessManager = null;
  57858. }
  57859. this.clearPostProcesses(true);
  57860. if (this._resizeObserver) {
  57861. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57862. this._resizeObserver = null;
  57863. }
  57864. this.renderList = null;
  57865. // Remove from custom render targets
  57866. var scene = this.getScene();
  57867. if (!scene) {
  57868. return;
  57869. }
  57870. var index = scene.customRenderTargets.indexOf(this);
  57871. if (index >= 0) {
  57872. scene.customRenderTargets.splice(index, 1);
  57873. }
  57874. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57875. var camera = _a[_i];
  57876. index = camera.customRenderTargets.indexOf(this);
  57877. if (index >= 0) {
  57878. camera.customRenderTargets.splice(index, 1);
  57879. }
  57880. }
  57881. _super.prototype.dispose.call(this);
  57882. };
  57883. RenderTargetTexture.prototype._rebuild = function () {
  57884. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57885. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57886. }
  57887. if (this._postProcessManager) {
  57888. this._postProcessManager._rebuild();
  57889. }
  57890. };
  57891. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57892. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57893. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57894. return RenderTargetTexture;
  57895. }(BABYLON.Texture));
  57896. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57897. })(BABYLON || (BABYLON = {}));
  57898. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57899. var BABYLON;
  57900. (function (BABYLON) {
  57901. ;
  57902. var MultiRenderTarget = /** @class */ (function (_super) {
  57903. __extends(MultiRenderTarget, _super);
  57904. function MultiRenderTarget(name, size, count, scene, options) {
  57905. var _this = this;
  57906. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57907. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57908. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57909. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57910. _this._engine = scene.getEngine();
  57911. if (!_this.isSupported) {
  57912. _this.dispose();
  57913. return;
  57914. }
  57915. var types = [];
  57916. var samplingModes = [];
  57917. for (var i = 0; i < count; i++) {
  57918. if (options && options.types && options.types[i] !== undefined) {
  57919. types.push(options.types[i]);
  57920. }
  57921. else {
  57922. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57923. }
  57924. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57925. samplingModes.push(options.samplingModes[i]);
  57926. }
  57927. else {
  57928. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57929. }
  57930. }
  57931. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57932. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57933. _this._size = size;
  57934. _this._multiRenderTargetOptions = {
  57935. samplingModes: samplingModes,
  57936. generateMipMaps: generateMipMaps,
  57937. generateDepthBuffer: generateDepthBuffer,
  57938. generateStencilBuffer: generateStencilBuffer,
  57939. generateDepthTexture: generateDepthTexture,
  57940. types: types,
  57941. textureCount: count
  57942. };
  57943. _this._createInternalTextures();
  57944. _this._createTextures();
  57945. return _this;
  57946. }
  57947. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57948. get: function () {
  57949. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57950. },
  57951. enumerable: true,
  57952. configurable: true
  57953. });
  57954. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57955. get: function () {
  57956. return this._textures;
  57957. },
  57958. enumerable: true,
  57959. configurable: true
  57960. });
  57961. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57962. get: function () {
  57963. return this._textures[this._textures.length - 1];
  57964. },
  57965. enumerable: true,
  57966. configurable: true
  57967. });
  57968. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57969. set: function (wrap) {
  57970. if (this._textures) {
  57971. for (var i = 0; i < this._textures.length; i++) {
  57972. this._textures[i].wrapU = wrap;
  57973. }
  57974. }
  57975. },
  57976. enumerable: true,
  57977. configurable: true
  57978. });
  57979. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57980. set: function (wrap) {
  57981. if (this._textures) {
  57982. for (var i = 0; i < this._textures.length; i++) {
  57983. this._textures[i].wrapV = wrap;
  57984. }
  57985. }
  57986. },
  57987. enumerable: true,
  57988. configurable: true
  57989. });
  57990. MultiRenderTarget.prototype._rebuild = function () {
  57991. this.releaseInternalTextures();
  57992. this._createInternalTextures();
  57993. for (var i = 0; i < this._internalTextures.length; i++) {
  57994. var texture = this._textures[i];
  57995. texture._texture = this._internalTextures[i];
  57996. }
  57997. // Keeps references to frame buffer and stencil/depth buffer
  57998. this._texture = this._internalTextures[0];
  57999. };
  58000. MultiRenderTarget.prototype._createInternalTextures = function () {
  58001. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58002. };
  58003. MultiRenderTarget.prototype._createTextures = function () {
  58004. this._textures = [];
  58005. for (var i = 0; i < this._internalTextures.length; i++) {
  58006. var texture = new BABYLON.Texture(null, this.getScene());
  58007. texture._texture = this._internalTextures[i];
  58008. this._textures.push(texture);
  58009. }
  58010. // Keeps references to frame buffer and stencil/depth buffer
  58011. this._texture = this._internalTextures[0];
  58012. };
  58013. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58014. get: function () {
  58015. return this._samples;
  58016. },
  58017. set: function (value) {
  58018. if (this._samples === value) {
  58019. return;
  58020. }
  58021. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58022. },
  58023. enumerable: true,
  58024. configurable: true
  58025. });
  58026. MultiRenderTarget.prototype.resize = function (size) {
  58027. this.releaseInternalTextures();
  58028. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58029. this._createInternalTextures();
  58030. };
  58031. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58032. var _this = this;
  58033. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58034. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58035. });
  58036. };
  58037. MultiRenderTarget.prototype.dispose = function () {
  58038. this.releaseInternalTextures();
  58039. _super.prototype.dispose.call(this);
  58040. };
  58041. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58042. if (!this._internalTextures) {
  58043. return;
  58044. }
  58045. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58046. if (this._internalTextures[i] !== undefined) {
  58047. this._internalTextures[i].dispose();
  58048. this._internalTextures.splice(i, 1);
  58049. }
  58050. }
  58051. };
  58052. return MultiRenderTarget;
  58053. }(BABYLON.RenderTargetTexture));
  58054. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58055. })(BABYLON || (BABYLON = {}));
  58056. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58057. var BABYLON;
  58058. (function (BABYLON) {
  58059. var MirrorTexture = /** @class */ (function (_super) {
  58060. __extends(MirrorTexture, _super);
  58061. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58062. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58064. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58065. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58066. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58067. _this._transformMatrix = BABYLON.Matrix.Zero();
  58068. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58069. _this._adaptiveBlurKernel = 0;
  58070. _this._blurKernelX = 0;
  58071. _this._blurKernelY = 0;
  58072. _this._blurRatio = 1.0;
  58073. _this.ignoreCameraViewport = true;
  58074. _this.onBeforeRenderObservable.add(function () {
  58075. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58076. _this._savedViewMatrix = scene.getViewMatrix();
  58077. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58078. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58079. scene.clipPlane = _this.mirrorPlane;
  58080. scene.getEngine().cullBackFaces = false;
  58081. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58082. });
  58083. _this.onAfterRenderObservable.add(function () {
  58084. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58085. scene.getEngine().cullBackFaces = true;
  58086. scene._mirroredCameraPosition = null;
  58087. delete scene.clipPlane;
  58088. });
  58089. return _this;
  58090. }
  58091. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58092. get: function () {
  58093. return this._blurRatio;
  58094. },
  58095. set: function (value) {
  58096. if (this._blurRatio === value) {
  58097. return;
  58098. }
  58099. this._blurRatio = value;
  58100. this._preparePostProcesses();
  58101. },
  58102. enumerable: true,
  58103. configurable: true
  58104. });
  58105. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58106. set: function (value) {
  58107. this._adaptiveBlurKernel = value;
  58108. this._autoComputeBlurKernel();
  58109. },
  58110. enumerable: true,
  58111. configurable: true
  58112. });
  58113. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58114. set: function (value) {
  58115. this.blurKernelX = value;
  58116. this.blurKernelY = value;
  58117. },
  58118. enumerable: true,
  58119. configurable: true
  58120. });
  58121. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58122. get: function () {
  58123. return this._blurKernelX;
  58124. },
  58125. set: function (value) {
  58126. if (this._blurKernelX === value) {
  58127. return;
  58128. }
  58129. this._blurKernelX = value;
  58130. this._preparePostProcesses();
  58131. },
  58132. enumerable: true,
  58133. configurable: true
  58134. });
  58135. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58136. get: function () {
  58137. return this._blurKernelY;
  58138. },
  58139. set: function (value) {
  58140. if (this._blurKernelY === value) {
  58141. return;
  58142. }
  58143. this._blurKernelY = value;
  58144. this._preparePostProcesses();
  58145. },
  58146. enumerable: true,
  58147. configurable: true
  58148. });
  58149. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58150. var engine = this.getScene().getEngine();
  58151. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58152. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58153. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58154. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58155. };
  58156. MirrorTexture.prototype._onRatioRescale = function () {
  58157. if (this._sizeRatio) {
  58158. this.resize(this._initialSizeParameter);
  58159. if (!this._adaptiveBlurKernel) {
  58160. this._preparePostProcesses();
  58161. }
  58162. }
  58163. if (this._adaptiveBlurKernel) {
  58164. this._autoComputeBlurKernel();
  58165. }
  58166. };
  58167. MirrorTexture.prototype._preparePostProcesses = function () {
  58168. this.clearPostProcesses(true);
  58169. if (this._blurKernelX && this._blurKernelY) {
  58170. var engine = this.getScene().getEngine();
  58171. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58172. 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);
  58173. this._blurX.autoClear = false;
  58174. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58175. this._blurX.inputTexture = this._texture;
  58176. }
  58177. else {
  58178. this._blurX.alwaysForcePOT = true;
  58179. }
  58180. 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);
  58181. this._blurY.autoClear = false;
  58182. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58183. this.addPostProcess(this._blurX);
  58184. this.addPostProcess(this._blurY);
  58185. }
  58186. else {
  58187. if (this._blurY) {
  58188. this.removePostProcess(this._blurY);
  58189. this._blurY.dispose();
  58190. this._blurY = null;
  58191. }
  58192. if (this._blurX) {
  58193. this.removePostProcess(this._blurX);
  58194. this._blurX.dispose();
  58195. this._blurX = null;
  58196. }
  58197. }
  58198. };
  58199. MirrorTexture.prototype.clone = function () {
  58200. var scene = this.getScene();
  58201. if (!scene) {
  58202. return this;
  58203. }
  58204. var textureSize = this.getSize();
  58205. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58206. // Base texture
  58207. newTexture.hasAlpha = this.hasAlpha;
  58208. newTexture.level = this.level;
  58209. // Mirror Texture
  58210. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58211. if (this.renderList) {
  58212. newTexture.renderList = this.renderList.slice(0);
  58213. }
  58214. return newTexture;
  58215. };
  58216. MirrorTexture.prototype.serialize = function () {
  58217. if (!this.name) {
  58218. return null;
  58219. }
  58220. var serializationObject = _super.prototype.serialize.call(this);
  58221. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58222. return serializationObject;
  58223. };
  58224. return MirrorTexture;
  58225. }(BABYLON.RenderTargetTexture));
  58226. BABYLON.MirrorTexture = MirrorTexture;
  58227. })(BABYLON || (BABYLON = {}));
  58228. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58229. var BABYLON;
  58230. (function (BABYLON) {
  58231. /**
  58232. * Creates a refraction texture used by refraction channel of the standard material.
  58233. * @param name the texture name
  58234. * @param size size of the underlying texture
  58235. * @param scene root scene
  58236. */
  58237. var RefractionTexture = /** @class */ (function (_super) {
  58238. __extends(RefractionTexture, _super);
  58239. function RefractionTexture(name, size, scene, generateMipMaps) {
  58240. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58241. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58242. _this.depth = 2.0;
  58243. _this.onBeforeRenderObservable.add(function () {
  58244. scene.clipPlane = _this.refractionPlane;
  58245. });
  58246. _this.onAfterRenderObservable.add(function () {
  58247. delete scene.clipPlane;
  58248. });
  58249. return _this;
  58250. }
  58251. RefractionTexture.prototype.clone = function () {
  58252. var scene = this.getScene();
  58253. if (!scene) {
  58254. return this;
  58255. }
  58256. var textureSize = this.getSize();
  58257. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58258. // Base texture
  58259. newTexture.hasAlpha = this.hasAlpha;
  58260. newTexture.level = this.level;
  58261. // Refraction Texture
  58262. newTexture.refractionPlane = this.refractionPlane.clone();
  58263. if (this.renderList) {
  58264. newTexture.renderList = this.renderList.slice(0);
  58265. }
  58266. newTexture.depth = this.depth;
  58267. return newTexture;
  58268. };
  58269. RefractionTexture.prototype.serialize = function () {
  58270. if (!this.name) {
  58271. return null;
  58272. }
  58273. var serializationObject = _super.prototype.serialize.call(this);
  58274. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58275. serializationObject.depth = this.depth;
  58276. return serializationObject;
  58277. };
  58278. return RefractionTexture;
  58279. }(BABYLON.RenderTargetTexture));
  58280. BABYLON.RefractionTexture = RefractionTexture;
  58281. })(BABYLON || (BABYLON = {}));
  58282. //# sourceMappingURL=babylon.refractionTexture.js.map
  58283. var BABYLON;
  58284. (function (BABYLON) {
  58285. var DynamicTexture = /** @class */ (function (_super) {
  58286. __extends(DynamicTexture, _super);
  58287. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58288. if (scene === void 0) { scene = null; }
  58289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58290. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58291. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58292. _this.name = name;
  58293. _this._engine = _this.getScene().getEngine();
  58294. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58295. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58296. _this._generateMipMaps = generateMipMaps;
  58297. if (options.getContext) {
  58298. _this._canvas = options;
  58299. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58300. }
  58301. else {
  58302. _this._canvas = document.createElement("canvas");
  58303. if (options.width) {
  58304. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58305. }
  58306. else {
  58307. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58308. }
  58309. }
  58310. var textureSize = _this.getSize();
  58311. _this._canvas.width = textureSize.width;
  58312. _this._canvas.height = textureSize.height;
  58313. _this._context = _this._canvas.getContext("2d");
  58314. return _this;
  58315. }
  58316. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58317. get: function () {
  58318. return true;
  58319. },
  58320. enumerable: true,
  58321. configurable: true
  58322. });
  58323. DynamicTexture.prototype._recreate = function (textureSize) {
  58324. this._canvas.width = textureSize.width;
  58325. this._canvas.height = textureSize.height;
  58326. this.releaseInternalTexture();
  58327. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58328. };
  58329. DynamicTexture.prototype.scale = function (ratio) {
  58330. var textureSize = this.getSize();
  58331. textureSize.width *= ratio;
  58332. textureSize.height *= ratio;
  58333. this._recreate(textureSize);
  58334. };
  58335. DynamicTexture.prototype.scaleTo = function (width, height) {
  58336. var textureSize = this.getSize();
  58337. textureSize.width = width;
  58338. textureSize.height = height;
  58339. this._recreate(textureSize);
  58340. };
  58341. DynamicTexture.prototype.getContext = function () {
  58342. return this._context;
  58343. };
  58344. DynamicTexture.prototype.clear = function () {
  58345. var size = this.getSize();
  58346. this._context.fillRect(0, 0, size.width, size.height);
  58347. };
  58348. DynamicTexture.prototype.update = function (invertY) {
  58349. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58350. };
  58351. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58352. if (update === void 0) { update = true; }
  58353. var size = this.getSize();
  58354. if (clearColor) {
  58355. this._context.fillStyle = clearColor;
  58356. this._context.fillRect(0, 0, size.width, size.height);
  58357. }
  58358. this._context.font = font;
  58359. if (x === null || x === undefined) {
  58360. var textSize = this._context.measureText(text);
  58361. x = (size.width - textSize.width) / 2;
  58362. }
  58363. if (y === null || y === undefined) {
  58364. var fontSize = parseInt((font.replace(/\D/g, '')));
  58365. ;
  58366. y = (size.height / 2) + (fontSize / 3.65);
  58367. }
  58368. this._context.fillStyle = color;
  58369. this._context.fillText(text, x, y);
  58370. if (update) {
  58371. this.update(invertY);
  58372. }
  58373. };
  58374. DynamicTexture.prototype.clone = function () {
  58375. var scene = this.getScene();
  58376. if (!scene) {
  58377. return this;
  58378. }
  58379. var textureSize = this.getSize();
  58380. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58381. // Base texture
  58382. newTexture.hasAlpha = this.hasAlpha;
  58383. newTexture.level = this.level;
  58384. // Dynamic Texture
  58385. newTexture.wrapU = this.wrapU;
  58386. newTexture.wrapV = this.wrapV;
  58387. return newTexture;
  58388. };
  58389. DynamicTexture.prototype._rebuild = function () {
  58390. this.update();
  58391. };
  58392. return DynamicTexture;
  58393. }(BABYLON.Texture));
  58394. BABYLON.DynamicTexture = DynamicTexture;
  58395. })(BABYLON || (BABYLON = {}));
  58396. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58397. var BABYLON;
  58398. (function (BABYLON) {
  58399. var VideoTexture = /** @class */ (function (_super) {
  58400. __extends(VideoTexture, _super);
  58401. /**
  58402. * Creates a video texture.
  58403. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58404. * @param {string | null} name optional name, will detect from video source, if not defined
  58405. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58406. * @param {BABYLON.Scene} scene is obviously the current scene.
  58407. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58408. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58409. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58410. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58411. */
  58412. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58413. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58414. if (invertY === void 0) { invertY = false; }
  58415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58416. if (settings === void 0) { settings = {
  58417. autoPlay: true,
  58418. loop: true,
  58419. autoUpdateTexture: true,
  58420. }; }
  58421. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58422. _this._createInternalTexture = function () {
  58423. if (_this._texture != null) {
  58424. return;
  58425. }
  58426. if (!_this._engine.needPOTTextures ||
  58427. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58428. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58429. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58430. }
  58431. else {
  58432. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58433. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58434. _this._generateMipMaps = false;
  58435. }
  58436. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58437. _this._texture.isReady = true;
  58438. _this._updateInternalTexture();
  58439. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  58440. _this.onLoadObservable.notifyObservers(_this);
  58441. }
  58442. };
  58443. _this.reset = function () {
  58444. if (_this._texture == null) {
  58445. return;
  58446. }
  58447. _this._texture.dispose();
  58448. _this._texture = null;
  58449. };
  58450. _this._updateInternalTexture = function (e) {
  58451. if (_this._texture == null || !_this._texture.isReady) {
  58452. return;
  58453. }
  58454. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58455. return;
  58456. }
  58457. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58458. };
  58459. _this._engine = _this.getScene().getEngine();
  58460. _this._generateMipMaps = generateMipMaps;
  58461. _this._samplingMode = samplingMode;
  58462. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58463. _this.name = name || _this._getName(src);
  58464. _this.video = _this._getVideo(src);
  58465. if (settings.autoPlay !== undefined) {
  58466. _this.video.autoplay = settings.autoPlay;
  58467. }
  58468. if (settings.loop !== undefined) {
  58469. _this.video.loop = settings.loop;
  58470. }
  58471. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58472. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58473. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58474. _this.video.addEventListener("emptied", _this.reset);
  58475. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58476. _this._createInternalTexture();
  58477. }
  58478. return _this;
  58479. }
  58480. VideoTexture.prototype._getName = function (src) {
  58481. if (src instanceof HTMLVideoElement) {
  58482. return src.currentSrc;
  58483. }
  58484. if (typeof src === "object") {
  58485. return src.toString();
  58486. }
  58487. return src;
  58488. };
  58489. ;
  58490. VideoTexture.prototype._getVideo = function (src) {
  58491. if (src instanceof HTMLVideoElement) {
  58492. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58493. return src;
  58494. }
  58495. var video = document.createElement("video");
  58496. if (typeof src === "string") {
  58497. BABYLON.Tools.SetCorsBehavior(src, video);
  58498. video.src = src;
  58499. }
  58500. else {
  58501. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58502. src.forEach(function (url) {
  58503. var source = document.createElement("source");
  58504. source.src = url;
  58505. video.appendChild(source);
  58506. });
  58507. }
  58508. return video;
  58509. };
  58510. ;
  58511. /**
  58512. * Internal method to initiate `update`.
  58513. */
  58514. VideoTexture.prototype._rebuild = function () {
  58515. this.update();
  58516. };
  58517. /**
  58518. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58519. */
  58520. VideoTexture.prototype.update = function () {
  58521. if (!this.autoUpdateTexture) {
  58522. // Expecting user to call `updateTexture` manually
  58523. return;
  58524. }
  58525. this.updateTexture(true);
  58526. };
  58527. /**
  58528. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58529. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58530. */
  58531. VideoTexture.prototype.updateTexture = function (isVisible) {
  58532. if (!isVisible) {
  58533. return;
  58534. }
  58535. if (this.video.paused) {
  58536. return;
  58537. }
  58538. this._updateInternalTexture();
  58539. };
  58540. /**
  58541. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58542. * @param url New url.
  58543. */
  58544. VideoTexture.prototype.updateURL = function (url) {
  58545. this.video.src = url;
  58546. };
  58547. VideoTexture.prototype.dispose = function () {
  58548. _super.prototype.dispose.call(this);
  58549. this.video.removeEventListener("canplay", this._createInternalTexture);
  58550. this.video.removeEventListener("paused", this._updateInternalTexture);
  58551. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58552. this.video.removeEventListener("emptied", this.reset);
  58553. this.video.pause();
  58554. };
  58555. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58556. var video = document.createElement("video");
  58557. var constraintsDeviceId;
  58558. if (constraints && constraints.deviceId) {
  58559. constraintsDeviceId = {
  58560. exact: constraints.deviceId,
  58561. };
  58562. }
  58563. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58564. if (navigator.mediaDevices) {
  58565. navigator.mediaDevices.getUserMedia({ video: constraints })
  58566. .then(function (stream) {
  58567. if (video.mozSrcObject !== undefined) {
  58568. // hack for Firefox < 19
  58569. video.mozSrcObject = stream;
  58570. }
  58571. else {
  58572. video.srcObject = stream;
  58573. }
  58574. var onPlaying = function () {
  58575. if (onReady) {
  58576. onReady(new VideoTexture("video", video, scene, true, true));
  58577. }
  58578. video.removeEventListener("playing", onPlaying);
  58579. };
  58580. video.addEventListener("playing", onPlaying);
  58581. video.play();
  58582. })
  58583. .catch(function (err) {
  58584. BABYLON.Tools.Error(err.name);
  58585. });
  58586. }
  58587. else {
  58588. navigator.getUserMedia =
  58589. navigator.getUserMedia ||
  58590. navigator.webkitGetUserMedia ||
  58591. navigator.mozGetUserMedia ||
  58592. navigator.msGetUserMedia;
  58593. if (navigator.getUserMedia) {
  58594. navigator.getUserMedia({
  58595. video: {
  58596. deviceId: constraintsDeviceId,
  58597. width: {
  58598. min: (constraints && constraints.minWidth) || 256,
  58599. max: (constraints && constraints.maxWidth) || 640,
  58600. },
  58601. height: {
  58602. min: (constraints && constraints.minHeight) || 256,
  58603. max: (constraints && constraints.maxHeight) || 480,
  58604. },
  58605. },
  58606. }, function (stream) {
  58607. if (video.mozSrcObject !== undefined) {
  58608. // hack for Firefox < 19
  58609. video.mozSrcObject = stream;
  58610. }
  58611. else {
  58612. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58613. }
  58614. video.play();
  58615. if (onReady) {
  58616. onReady(new VideoTexture("video", video, scene, true, true));
  58617. }
  58618. }, function (e) {
  58619. BABYLON.Tools.Error(e.name);
  58620. });
  58621. }
  58622. }
  58623. };
  58624. return VideoTexture;
  58625. }(BABYLON.Texture));
  58626. BABYLON.VideoTexture = VideoTexture;
  58627. })(BABYLON || (BABYLON = {}));
  58628. //# sourceMappingURL=babylon.videoTexture.js.map
  58629. var BABYLON;
  58630. (function (BABYLON) {
  58631. var RawTexture = /** @class */ (function (_super) {
  58632. __extends(RawTexture, _super);
  58633. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58634. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58635. if (invertY === void 0) { invertY = false; }
  58636. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58637. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58638. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58639. _this.format = format;
  58640. _this._engine = scene.getEngine();
  58641. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58642. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58643. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58644. return _this;
  58645. }
  58646. RawTexture.prototype.update = function (data) {
  58647. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58648. };
  58649. // Statics
  58650. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58651. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58652. if (invertY === void 0) { invertY = false; }
  58653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58654. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58655. };
  58656. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58657. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58658. if (invertY === void 0) { invertY = false; }
  58659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58660. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58661. };
  58662. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58663. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58664. if (invertY === void 0) { invertY = false; }
  58665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58666. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58667. };
  58668. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58669. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58670. if (invertY === void 0) { invertY = false; }
  58671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58672. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58673. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58674. };
  58675. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58676. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58677. if (invertY === void 0) { invertY = false; }
  58678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58679. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58680. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58681. };
  58682. return RawTexture;
  58683. }(BABYLON.Texture));
  58684. BABYLON.RawTexture = RawTexture;
  58685. })(BABYLON || (BABYLON = {}));
  58686. //# sourceMappingURL=babylon.rawTexture.js.map
  58687. var BABYLON;
  58688. (function (BABYLON) {
  58689. /**
  58690. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58691. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58692. */
  58693. var PostProcess = /** @class */ (function () {
  58694. /**
  58695. * Creates a new instance of @see PostProcess
  58696. * @param name The name of the PostProcess.
  58697. * @param fragmentUrl The url of the fragment shader to be used.
  58698. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58699. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58700. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58701. * @param camera The camera to apply the render pass to.
  58702. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58703. * @param engine The engine which the post process will be applied. (default: current engine)
  58704. * @param reusable If the post process can be reused on the same frame. (default: false)
  58705. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58706. * @param textureType Type of textures used when performing the post process. (default: 0)
  58707. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58708. * @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
  58709. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58710. */
  58711. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58713. if (defines === void 0) { defines = null; }
  58714. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58715. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58716. if (blockCompilation === void 0) { blockCompilation = false; }
  58717. this.name = name;
  58718. /**
  58719. * Width of the texture to apply the post process on
  58720. */
  58721. this.width = -1;
  58722. /**
  58723. * Height of the texture to apply the post process on
  58724. */
  58725. this.height = -1;
  58726. /**
  58727. * If the buffer needs to be cleared before applying the post process. (default: true)
  58728. * Should be set to false if shader will overwrite all previous pixels.
  58729. */
  58730. this.autoClear = true;
  58731. /**
  58732. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58733. */
  58734. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58735. /**
  58736. * Animations to be used for the post processing
  58737. */
  58738. this.animations = new Array();
  58739. /**
  58740. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58741. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58742. */
  58743. this.enablePixelPerfectMode = false;
  58744. /**
  58745. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58746. */
  58747. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58748. /**
  58749. * Force textures to be a power of two (default: false)
  58750. */
  58751. this.alwaysForcePOT = false;
  58752. /**
  58753. * Number of sample textures (default: 1)
  58754. */
  58755. this.samples = 1;
  58756. /**
  58757. * Modify the scale of the post process to be the same as the viewport (default: false)
  58758. */
  58759. this.adaptScaleToCurrentViewport = false;
  58760. this._reusable = false;
  58761. /**
  58762. * Smart array of input and output textures for the post process.
  58763. */
  58764. this._textures = new BABYLON.SmartArray(2);
  58765. /**
  58766. * The index in _textures that corresponds to the output texture.
  58767. */
  58768. this._currentRenderTextureInd = 0;
  58769. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58770. this._texelSize = BABYLON.Vector2.Zero();
  58771. // Events
  58772. /**
  58773. * An event triggered when the postprocess is activated.
  58774. * @type {BABYLON.Observable}
  58775. */
  58776. this.onActivateObservable = new BABYLON.Observable();
  58777. /**
  58778. * An event triggered when the postprocess changes its size.
  58779. * @type {BABYLON.Observable}
  58780. */
  58781. this.onSizeChangedObservable = new BABYLON.Observable();
  58782. /**
  58783. * An event triggered when the postprocess applies its effect.
  58784. * @type {BABYLON.Observable}
  58785. */
  58786. this.onApplyObservable = new BABYLON.Observable();
  58787. /**
  58788. * An event triggered before rendering the postprocess
  58789. * @type {BABYLON.Observable}
  58790. */
  58791. this.onBeforeRenderObservable = new BABYLON.Observable();
  58792. /**
  58793. * An event triggered after rendering the postprocess
  58794. * @type {BABYLON.Observable}
  58795. */
  58796. this.onAfterRenderObservable = new BABYLON.Observable();
  58797. if (camera != null) {
  58798. this._camera = camera;
  58799. this._scene = camera.getScene();
  58800. camera.attachPostProcess(this);
  58801. this._engine = this._scene.getEngine();
  58802. this._scene.postProcesses.push(this);
  58803. }
  58804. else if (engine) {
  58805. this._engine = engine;
  58806. this._engine.postProcesses.push(this);
  58807. }
  58808. this._options = options;
  58809. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58810. this._reusable = reusable || false;
  58811. this._textureType = textureType;
  58812. this._samplers = samplers || [];
  58813. this._samplers.push("textureSampler");
  58814. this._fragmentUrl = fragmentUrl;
  58815. this._vertexUrl = vertexUrl;
  58816. this._parameters = parameters || [];
  58817. this._parameters.push("scale");
  58818. this._indexParameters = indexParameters;
  58819. if (!blockCompilation) {
  58820. this.updateEffect(defines);
  58821. }
  58822. }
  58823. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58824. /**
  58825. * A function that is added to the onActivateObservable
  58826. */
  58827. set: function (callback) {
  58828. if (this._onActivateObserver) {
  58829. this.onActivateObservable.remove(this._onActivateObserver);
  58830. }
  58831. if (callback) {
  58832. this._onActivateObserver = this.onActivateObservable.add(callback);
  58833. }
  58834. },
  58835. enumerable: true,
  58836. configurable: true
  58837. });
  58838. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58839. /**
  58840. * A function that is added to the onSizeChangedObservable
  58841. */
  58842. set: function (callback) {
  58843. if (this._onSizeChangedObserver) {
  58844. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58845. }
  58846. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58847. },
  58848. enumerable: true,
  58849. configurable: true
  58850. });
  58851. Object.defineProperty(PostProcess.prototype, "onApply", {
  58852. /**
  58853. * A function that is added to the onApplyObservable
  58854. */
  58855. set: function (callback) {
  58856. if (this._onApplyObserver) {
  58857. this.onApplyObservable.remove(this._onApplyObserver);
  58858. }
  58859. this._onApplyObserver = this.onApplyObservable.add(callback);
  58860. },
  58861. enumerable: true,
  58862. configurable: true
  58863. });
  58864. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58865. /**
  58866. * A function that is added to the onBeforeRenderObservable
  58867. */
  58868. set: function (callback) {
  58869. if (this._onBeforeRenderObserver) {
  58870. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58871. }
  58872. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58873. },
  58874. enumerable: true,
  58875. configurable: true
  58876. });
  58877. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58878. /**
  58879. * A function that is added to the onAfterRenderObservable
  58880. */
  58881. set: function (callback) {
  58882. if (this._onAfterRenderObserver) {
  58883. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58884. }
  58885. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58886. },
  58887. enumerable: true,
  58888. configurable: true
  58889. });
  58890. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58891. /**
  58892. * 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
  58893. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58894. */
  58895. get: function () {
  58896. return this._textures.data[this._currentRenderTextureInd];
  58897. },
  58898. set: function (value) {
  58899. this._forcedOutputTexture = value;
  58900. },
  58901. enumerable: true,
  58902. configurable: true
  58903. });
  58904. /**
  58905. * Gets the camera which post process is applied to.
  58906. * @returns The camera the post process is applied to.
  58907. */
  58908. PostProcess.prototype.getCamera = function () {
  58909. return this._camera;
  58910. };
  58911. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58912. /**
  58913. * Gets the texel size of the postprocess.
  58914. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58915. */
  58916. get: function () {
  58917. if (this._shareOutputWithPostProcess) {
  58918. return this._shareOutputWithPostProcess.texelSize;
  58919. }
  58920. if (this._forcedOutputTexture) {
  58921. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58922. }
  58923. return this._texelSize;
  58924. },
  58925. enumerable: true,
  58926. configurable: true
  58927. });
  58928. /**
  58929. * Gets the engine which this post process belongs to.
  58930. * @returns The engine the post process was enabled with.
  58931. */
  58932. PostProcess.prototype.getEngine = function () {
  58933. return this._engine;
  58934. };
  58935. /**
  58936. * The effect that is created when initializing the post process.
  58937. * @returns The created effect corrisponding the the postprocess.
  58938. */
  58939. PostProcess.prototype.getEffect = function () {
  58940. return this._effect;
  58941. };
  58942. /**
  58943. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58944. * @param postProcess The post process to share the output with.
  58945. * @returns This post process.
  58946. */
  58947. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58948. this._disposeTextures();
  58949. this._shareOutputWithPostProcess = postProcess;
  58950. return this;
  58951. };
  58952. /**
  58953. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  58954. * This should be called if the post process that shares output with this post process is disabled/disposed.
  58955. */
  58956. PostProcess.prototype.useOwnOutput = function () {
  58957. if (this._textures.length == 0) {
  58958. this._textures = new BABYLON.SmartArray(2);
  58959. }
  58960. this._shareOutputWithPostProcess = null;
  58961. };
  58962. /**
  58963. * Updates the effect with the current post process compile time values and recompiles the shader.
  58964. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58965. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58966. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58967. * @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
  58968. * @param onCompiled Called when the shader has been compiled.
  58969. * @param onError Called if there is an error when compiling a shader.
  58970. */
  58971. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58972. if (defines === void 0) { defines = null; }
  58973. if (uniforms === void 0) { uniforms = null; }
  58974. if (samplers === void 0) { samplers = null; }
  58975. 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);
  58976. };
  58977. /**
  58978. * The post process is reusable if it can be used multiple times within one frame.
  58979. * @returns If the post process is reusable
  58980. */
  58981. PostProcess.prototype.isReusable = function () {
  58982. return this._reusable;
  58983. };
  58984. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58985. PostProcess.prototype.markTextureDirty = function () {
  58986. this.width = -1;
  58987. };
  58988. /**
  58989. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58990. * 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.
  58991. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58992. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58993. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58994. */
  58995. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58996. var _this = this;
  58997. if (sourceTexture === void 0) { sourceTexture = null; }
  58998. camera = camera || this._camera;
  58999. var scene = camera.getScene();
  59000. var engine = scene.getEngine();
  59001. var maxSize = engine.getCaps().maxTextureSize;
  59002. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59003. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59004. // 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
  59005. var webVRCamera = camera.parent;
  59006. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59007. requiredWidth /= 2;
  59008. }
  59009. var desiredWidth = (this._options.width || requiredWidth);
  59010. var desiredHeight = this._options.height || requiredHeight;
  59011. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59012. if (this.adaptScaleToCurrentViewport) {
  59013. var currentViewport = engine.currentViewport;
  59014. if (currentViewport) {
  59015. desiredWidth *= currentViewport.width;
  59016. desiredHeight *= currentViewport.height;
  59017. }
  59018. }
  59019. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59020. if (!this._options.width) {
  59021. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59022. }
  59023. if (!this._options.height) {
  59024. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59025. }
  59026. }
  59027. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59028. if (this._textures.length > 0) {
  59029. for (var i = 0; i < this._textures.length; i++) {
  59030. this._engine._releaseTexture(this._textures.data[i]);
  59031. }
  59032. this._textures.reset();
  59033. }
  59034. this.width = desiredWidth;
  59035. this.height = desiredHeight;
  59036. var textureSize = { width: this.width, height: this.height };
  59037. var textureOptions = {
  59038. generateMipMaps: false,
  59039. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59040. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59041. samplingMode: this.renderTargetSamplingMode,
  59042. type: this._textureType
  59043. };
  59044. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59045. if (this._reusable) {
  59046. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59047. }
  59048. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59049. this.onSizeChangedObservable.notifyObservers(this);
  59050. }
  59051. this._textures.forEach(function (texture) {
  59052. if (texture.samples !== _this.samples) {
  59053. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59054. }
  59055. });
  59056. }
  59057. var target;
  59058. if (this._shareOutputWithPostProcess) {
  59059. target = this._shareOutputWithPostProcess.inputTexture;
  59060. }
  59061. else if (this._forcedOutputTexture) {
  59062. target = this._forcedOutputTexture;
  59063. this.width = this._forcedOutputTexture.width;
  59064. this.height = this._forcedOutputTexture.height;
  59065. }
  59066. else {
  59067. target = this.inputTexture;
  59068. }
  59069. // Bind the input of this post process to be used as the output of the previous post process.
  59070. if (this.enablePixelPerfectMode) {
  59071. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59072. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59073. }
  59074. else {
  59075. this._scaleRatio.copyFromFloats(1, 1);
  59076. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59077. }
  59078. this.onActivateObservable.notifyObservers(camera);
  59079. // Clear
  59080. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59081. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59082. }
  59083. if (this._reusable) {
  59084. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59085. }
  59086. };
  59087. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59088. /**
  59089. * If the post process is supported.
  59090. */
  59091. get: function () {
  59092. return this._effect.isSupported;
  59093. },
  59094. enumerable: true,
  59095. configurable: true
  59096. });
  59097. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59098. /**
  59099. * The aspect ratio of the output texture.
  59100. */
  59101. get: function () {
  59102. if (this._shareOutputWithPostProcess) {
  59103. return this._shareOutputWithPostProcess.aspectRatio;
  59104. }
  59105. if (this._forcedOutputTexture) {
  59106. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59107. }
  59108. return this.width / this.height;
  59109. },
  59110. enumerable: true,
  59111. configurable: true
  59112. });
  59113. /**
  59114. * Get a value indicating if the post-process is ready to be used
  59115. * @returns true if the post-process is ready (shader is compiled)
  59116. */
  59117. PostProcess.prototype.isReady = function () {
  59118. return this._effect && this._effect.isReady();
  59119. };
  59120. /**
  59121. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59122. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59123. */
  59124. PostProcess.prototype.apply = function () {
  59125. // Check
  59126. if (!this._effect || !this._effect.isReady())
  59127. return null;
  59128. // States
  59129. this._engine.enableEffect(this._effect);
  59130. this._engine.setState(false);
  59131. this._engine.setDepthBuffer(false);
  59132. this._engine.setDepthWrite(false);
  59133. // Alpha
  59134. this._engine.setAlphaMode(this.alphaMode);
  59135. if (this.alphaConstants) {
  59136. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59137. }
  59138. // Bind the output texture of the preivous post process as the input to this post process.
  59139. var source;
  59140. if (this._shareOutputWithPostProcess) {
  59141. source = this._shareOutputWithPostProcess.inputTexture;
  59142. }
  59143. else if (this._forcedOutputTexture) {
  59144. source = this._forcedOutputTexture;
  59145. }
  59146. else {
  59147. source = this.inputTexture;
  59148. }
  59149. this._effect._bindTexture("textureSampler", source);
  59150. // Parameters
  59151. this._effect.setVector2("scale", this._scaleRatio);
  59152. this.onApplyObservable.notifyObservers(this._effect);
  59153. return this._effect;
  59154. };
  59155. PostProcess.prototype._disposeTextures = function () {
  59156. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59157. return;
  59158. }
  59159. if (this._textures.length > 0) {
  59160. for (var i = 0; i < this._textures.length; i++) {
  59161. this._engine._releaseTexture(this._textures.data[i]);
  59162. }
  59163. }
  59164. this._textures.dispose();
  59165. };
  59166. /**
  59167. * Disposes the post process.
  59168. * @param camera The camera to dispose the post process on.
  59169. */
  59170. PostProcess.prototype.dispose = function (camera) {
  59171. camera = camera || this._camera;
  59172. this._disposeTextures();
  59173. if (this._scene) {
  59174. var index_1 = this._scene.postProcesses.indexOf(this);
  59175. if (index_1 !== -1) {
  59176. this._scene.postProcesses.splice(index_1, 1);
  59177. }
  59178. }
  59179. else {
  59180. var index_2 = this._engine.postProcesses.indexOf(this);
  59181. if (index_2 !== -1) {
  59182. this._engine.postProcesses.splice(index_2, 1);
  59183. }
  59184. }
  59185. if (!camera) {
  59186. return;
  59187. }
  59188. camera.detachPostProcess(this);
  59189. var index = camera._postProcesses.indexOf(this);
  59190. if (index === 0 && camera._postProcesses.length > 0) {
  59191. this._camera._postProcesses[0].markTextureDirty();
  59192. }
  59193. this.onActivateObservable.clear();
  59194. this.onAfterRenderObservable.clear();
  59195. this.onApplyObservable.clear();
  59196. this.onBeforeRenderObservable.clear();
  59197. this.onSizeChangedObservable.clear();
  59198. };
  59199. return PostProcess;
  59200. }());
  59201. BABYLON.PostProcess = PostProcess;
  59202. })(BABYLON || (BABYLON = {}));
  59203. //# sourceMappingURL=babylon.postProcess.js.map
  59204. var BABYLON;
  59205. (function (BABYLON) {
  59206. var PassPostProcess = /** @class */ (function (_super) {
  59207. __extends(PassPostProcess, _super);
  59208. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59209. if (camera === void 0) { camera = null; }
  59210. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59211. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59212. }
  59213. return PassPostProcess;
  59214. }(BABYLON.PostProcess));
  59215. BABYLON.PassPostProcess = PassPostProcess;
  59216. })(BABYLON || (BABYLON = {}));
  59217. //# sourceMappingURL=babylon.passPostProcess.js.map
  59218. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59219. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59220. s = arguments[i];
  59221. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59222. t[p] = s[p];
  59223. }
  59224. return t;
  59225. };
  59226. var BABYLON;
  59227. (function (BABYLON) {
  59228. /**
  59229. * Default implementation of @see IShadowGenerator.
  59230. * This is the main object responsible of generating shadows in the framework.
  59231. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59232. */
  59233. var ShadowGenerator = /** @class */ (function () {
  59234. /**
  59235. * Creates a ShadowGenerator object.
  59236. * A ShadowGenerator is the required tool to use the shadows.
  59237. * Each light casting shadows needs to use its own ShadowGenerator.
  59238. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59239. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59240. * @param light The light object generating the shadows.
  59241. * @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.
  59242. */
  59243. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59244. this._bias = 0.00005;
  59245. this._blurBoxOffset = 1;
  59246. this._blurScale = 2;
  59247. this._blurKernel = 1;
  59248. this._useKernelBlur = false;
  59249. this._filter = ShadowGenerator.FILTER_NONE;
  59250. this._darkness = 0;
  59251. this._transparencyShadow = false;
  59252. /**
  59253. * Controls the extent to which the shadows fade out at the edge of the frustum
  59254. * Used only by directionals and spots
  59255. */
  59256. this.frustumEdgeFalloff = 0;
  59257. /**
  59258. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59259. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59260. * It might on the other hand introduce peter panning.
  59261. */
  59262. this.forceBackFacesOnly = false;
  59263. this._lightDirection = BABYLON.Vector3.Zero();
  59264. this._viewMatrix = BABYLON.Matrix.Zero();
  59265. this._projectionMatrix = BABYLON.Matrix.Zero();
  59266. this._transformMatrix = BABYLON.Matrix.Zero();
  59267. this._currentFaceIndex = 0;
  59268. this._currentFaceIndexCache = 0;
  59269. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59270. this._mapSize = mapSize;
  59271. this._light = light;
  59272. this._scene = light.getScene();
  59273. light._shadowGenerator = this;
  59274. // Texture type fallback from float to int if not supported.
  59275. var caps = this._scene.getEngine().getCaps();
  59276. if (!useFullFloatFirst) {
  59277. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59278. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59279. }
  59280. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59281. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59282. }
  59283. else {
  59284. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59285. }
  59286. }
  59287. else {
  59288. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59289. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59290. }
  59291. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59292. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59293. }
  59294. else {
  59295. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59296. }
  59297. }
  59298. this._initializeGenerator();
  59299. }
  59300. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59301. /**
  59302. * Shadow generator mode None: no filtering applied.
  59303. */
  59304. get: function () {
  59305. return ShadowGenerator._FILTER_NONE;
  59306. },
  59307. enumerable: true,
  59308. configurable: true
  59309. });
  59310. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59311. /**
  59312. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59313. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59314. */
  59315. get: function () {
  59316. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59317. },
  59318. enumerable: true,
  59319. configurable: true
  59320. });
  59321. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59322. /**
  59323. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59324. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59325. */
  59326. get: function () {
  59327. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59328. },
  59329. enumerable: true,
  59330. configurable: true
  59331. });
  59332. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59333. /**
  59334. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59335. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59336. */
  59337. get: function () {
  59338. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59339. },
  59340. enumerable: true,
  59341. configurable: true
  59342. });
  59343. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59344. /**
  59345. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59346. * edge artifacts on steep falloff.
  59347. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59348. */
  59349. get: function () {
  59350. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59351. },
  59352. enumerable: true,
  59353. configurable: true
  59354. });
  59355. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59356. /**
  59357. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59358. * edge artifacts on steep falloff.
  59359. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59360. */
  59361. get: function () {
  59362. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59363. },
  59364. enumerable: true,
  59365. configurable: true
  59366. });
  59367. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59368. /**
  59369. * Gets the bias: offset applied on the depth preventing acnea.
  59370. */
  59371. get: function () {
  59372. return this._bias;
  59373. },
  59374. /**
  59375. * Sets the bias: offset applied on the depth preventing acnea.
  59376. */
  59377. set: function (bias) {
  59378. this._bias = bias;
  59379. },
  59380. enumerable: true,
  59381. configurable: true
  59382. });
  59383. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59384. /**
  59385. * Gets the blur box offset: offset applied during the blur pass.
  59386. * Only usefull if useKernelBlur = false
  59387. */
  59388. get: function () {
  59389. return this._blurBoxOffset;
  59390. },
  59391. /**
  59392. * Sets the blur box offset: offset applied during the blur pass.
  59393. * Only usefull if useKernelBlur = false
  59394. */
  59395. set: function (value) {
  59396. if (this._blurBoxOffset === value) {
  59397. return;
  59398. }
  59399. this._blurBoxOffset = value;
  59400. this._disposeBlurPostProcesses();
  59401. },
  59402. enumerable: true,
  59403. configurable: true
  59404. });
  59405. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59406. /**
  59407. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59408. * 2 means half of the size.
  59409. */
  59410. get: function () {
  59411. return this._blurScale;
  59412. },
  59413. /**
  59414. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59415. * 2 means half of the size.
  59416. */
  59417. set: function (value) {
  59418. if (this._blurScale === value) {
  59419. return;
  59420. }
  59421. this._blurScale = value;
  59422. this._disposeBlurPostProcesses();
  59423. },
  59424. enumerable: true,
  59425. configurable: true
  59426. });
  59427. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59428. /**
  59429. * Gets the blur kernel: kernel size of the blur pass.
  59430. * Only usefull if useKernelBlur = true
  59431. */
  59432. get: function () {
  59433. return this._blurKernel;
  59434. },
  59435. /**
  59436. * Sets the blur kernel: kernel size of the blur pass.
  59437. * Only usefull if useKernelBlur = true
  59438. */
  59439. set: function (value) {
  59440. if (this._blurKernel === value) {
  59441. return;
  59442. }
  59443. this._blurKernel = value;
  59444. this._disposeBlurPostProcesses();
  59445. },
  59446. enumerable: true,
  59447. configurable: true
  59448. });
  59449. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59450. /**
  59451. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59452. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59453. */
  59454. get: function () {
  59455. return this._useKernelBlur;
  59456. },
  59457. /**
  59458. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59459. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59460. */
  59461. set: function (value) {
  59462. if (this._useKernelBlur === value) {
  59463. return;
  59464. }
  59465. this._useKernelBlur = value;
  59466. this._disposeBlurPostProcesses();
  59467. },
  59468. enumerable: true,
  59469. configurable: true
  59470. });
  59471. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59472. /**
  59473. * Gets the depth scale used in ESM mode.
  59474. */
  59475. get: function () {
  59476. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59477. },
  59478. /**
  59479. * Sets the depth scale used in ESM mode.
  59480. * This can override the scale stored on the light.
  59481. */
  59482. set: function (value) {
  59483. this._depthScale = value;
  59484. },
  59485. enumerable: true,
  59486. configurable: true
  59487. });
  59488. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59489. /**
  59490. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59491. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59492. */
  59493. get: function () {
  59494. return this._filter;
  59495. },
  59496. /**
  59497. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59498. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59499. */
  59500. set: function (value) {
  59501. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59502. if (this._light.needCube()) {
  59503. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59504. this.useExponentialShadowMap = true;
  59505. return;
  59506. }
  59507. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59508. this.useCloseExponentialShadowMap = true;
  59509. return;
  59510. }
  59511. }
  59512. if (this._filter === value) {
  59513. return;
  59514. }
  59515. this._filter = value;
  59516. this._disposeBlurPostProcesses();
  59517. this._applyFilterValues();
  59518. this._light._markMeshesAsLightDirty();
  59519. },
  59520. enumerable: true,
  59521. configurable: true
  59522. });
  59523. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59524. /**
  59525. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59526. */
  59527. get: function () {
  59528. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59529. },
  59530. /**
  59531. * Sets the current filter to Poisson Sampling aka PCF.
  59532. */
  59533. set: function (value) {
  59534. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59535. return;
  59536. }
  59537. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59538. },
  59539. enumerable: true,
  59540. configurable: true
  59541. });
  59542. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59543. /**
  59544. * Gets if the current filter is set to VSM.
  59545. * DEPRECATED. Should use useExponentialShadowMap instead.
  59546. */
  59547. get: function () {
  59548. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59549. return this.useExponentialShadowMap;
  59550. },
  59551. /**
  59552. * Sets the current filter is to VSM.
  59553. * DEPRECATED. Should use useExponentialShadowMap instead.
  59554. */
  59555. set: function (value) {
  59556. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59557. this.useExponentialShadowMap = value;
  59558. },
  59559. enumerable: true,
  59560. configurable: true
  59561. });
  59562. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59563. /**
  59564. * Gets if the current filter is set to blurred VSM.
  59565. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59566. */
  59567. get: function () {
  59568. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59569. return this.useBlurExponentialShadowMap;
  59570. },
  59571. /**
  59572. * Sets the current filter is to blurred VSM.
  59573. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59574. */
  59575. set: function (value) {
  59576. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59577. this.useBlurExponentialShadowMap = value;
  59578. },
  59579. enumerable: true,
  59580. configurable: true
  59581. });
  59582. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59583. /**
  59584. * Gets if the current filter is set to ESM.
  59585. */
  59586. get: function () {
  59587. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59588. },
  59589. /**
  59590. * Sets the current filter is to ESM.
  59591. */
  59592. set: function (value) {
  59593. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59594. return;
  59595. }
  59596. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59597. },
  59598. enumerable: true,
  59599. configurable: true
  59600. });
  59601. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59602. /**
  59603. * Gets if the current filter is set to filtered ESM.
  59604. */
  59605. get: function () {
  59606. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59607. },
  59608. /**
  59609. * Gets if the current filter is set to filtered ESM.
  59610. */
  59611. set: function (value) {
  59612. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59613. return;
  59614. }
  59615. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59616. },
  59617. enumerable: true,
  59618. configurable: true
  59619. });
  59620. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59621. /**
  59622. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59623. * exponential to prevent steep falloff artifacts).
  59624. */
  59625. get: function () {
  59626. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59627. },
  59628. /**
  59629. * Sets the current filter to "close ESM" (using the inverse of the
  59630. * exponential to prevent steep falloff artifacts).
  59631. */
  59632. set: function (value) {
  59633. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59634. return;
  59635. }
  59636. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59637. },
  59638. enumerable: true,
  59639. configurable: true
  59640. });
  59641. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59642. /**
  59643. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59644. * exponential to prevent steep falloff artifacts).
  59645. */
  59646. get: function () {
  59647. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59648. },
  59649. /**
  59650. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59651. * exponential to prevent steep falloff artifacts).
  59652. */
  59653. set: function (value) {
  59654. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59655. return;
  59656. }
  59657. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59658. },
  59659. enumerable: true,
  59660. configurable: true
  59661. });
  59662. /**
  59663. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59664. * 0 means strongest and 1 would means no shadow.
  59665. * @returns the darkness.
  59666. */
  59667. ShadowGenerator.prototype.getDarkness = function () {
  59668. return this._darkness;
  59669. };
  59670. /**
  59671. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59672. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59673. * @returns the shadow generator allowing fluent coding.
  59674. */
  59675. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59676. if (darkness >= 1.0)
  59677. this._darkness = 1.0;
  59678. else if (darkness <= 0.0)
  59679. this._darkness = 0.0;
  59680. else
  59681. this._darkness = darkness;
  59682. return this;
  59683. };
  59684. /**
  59685. * Sets the ability to have transparent shadow (boolean).
  59686. * @param transparent True if transparent else False
  59687. * @returns the shadow generator allowing fluent coding
  59688. */
  59689. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59690. this._transparencyShadow = transparent;
  59691. return this;
  59692. };
  59693. /**
  59694. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59695. * @returns The render target texture if present otherwise, null
  59696. */
  59697. ShadowGenerator.prototype.getShadowMap = function () {
  59698. return this._shadowMap;
  59699. };
  59700. /**
  59701. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59702. * @returns The render target texture if the shadow map is present otherwise, null
  59703. */
  59704. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59705. if (this._shadowMap2) {
  59706. return this._shadowMap2;
  59707. }
  59708. return this._shadowMap;
  59709. };
  59710. /**
  59711. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59712. * @param mesh Mesh to add
  59713. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59714. * @returns the Shadow Generator itself
  59715. */
  59716. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59717. if (includeDescendants === void 0) { includeDescendants = true; }
  59718. if (!this._shadowMap) {
  59719. return this;
  59720. }
  59721. if (!this._shadowMap.renderList) {
  59722. this._shadowMap.renderList = [];
  59723. }
  59724. this._shadowMap.renderList.push(mesh);
  59725. if (includeDescendants) {
  59726. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59727. }
  59728. return this;
  59729. var _a;
  59730. };
  59731. /**
  59732. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59733. * @param mesh Mesh to remove
  59734. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59735. * @returns the Shadow Generator itself
  59736. */
  59737. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59738. if (includeDescendants === void 0) { includeDescendants = true; }
  59739. if (!this._shadowMap || !this._shadowMap.renderList) {
  59740. return this;
  59741. }
  59742. var index = this._shadowMap.renderList.indexOf(mesh);
  59743. if (index !== -1) {
  59744. this._shadowMap.renderList.splice(index, 1);
  59745. }
  59746. if (includeDescendants) {
  59747. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59748. var child = _a[_i];
  59749. this.removeShadowCaster(child);
  59750. }
  59751. }
  59752. return this;
  59753. };
  59754. /**
  59755. * Returns the associated light object.
  59756. * @returns the light generating the shadow
  59757. */
  59758. ShadowGenerator.prototype.getLight = function () {
  59759. return this._light;
  59760. };
  59761. ShadowGenerator.prototype._initializeGenerator = function () {
  59762. this._light._markMeshesAsLightDirty();
  59763. this._initializeShadowMap();
  59764. };
  59765. ShadowGenerator.prototype._initializeShadowMap = function () {
  59766. var _this = this;
  59767. // Render target
  59768. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59769. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59770. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59771. this._shadowMap.anisotropicFilteringLevel = 1;
  59772. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59773. this._shadowMap.renderParticles = false;
  59774. this._shadowMap.ignoreCameraViewport = true;
  59775. // Record Face Index before render.
  59776. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59777. _this._currentFaceIndex = faceIndex;
  59778. });
  59779. // Custom render function.
  59780. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59781. // Blur if required afer render.
  59782. this._shadowMap.onAfterUnbindObservable.add(function () {
  59783. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59784. return;
  59785. }
  59786. var shadowMap = _this.getShadowMapForRendering();
  59787. if (shadowMap) {
  59788. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59789. }
  59790. });
  59791. // Clear according to the chosen filter.
  59792. this._shadowMap.onClearObservable.add(function (engine) {
  59793. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59794. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59795. }
  59796. else {
  59797. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59798. }
  59799. });
  59800. };
  59801. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59802. var _this = this;
  59803. var engine = this._scene.getEngine();
  59804. var targetSize = this._mapSize / this.blurScale;
  59805. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59806. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59807. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59808. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59809. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59810. }
  59811. if (this.useKernelBlur) {
  59812. 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);
  59813. this._kernelBlurXPostprocess.width = targetSize;
  59814. this._kernelBlurXPostprocess.height = targetSize;
  59815. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59816. effect.setTexture("textureSampler", _this._shadowMap);
  59817. });
  59818. 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);
  59819. this._kernelBlurXPostprocess.autoClear = false;
  59820. this._kernelBlurYPostprocess.autoClear = false;
  59821. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59822. this._kernelBlurXPostprocess.packedFloat = true;
  59823. this._kernelBlurYPostprocess.packedFloat = true;
  59824. }
  59825. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59826. }
  59827. else {
  59828. 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);
  59829. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59830. effect.setFloat2("screenSize", targetSize, targetSize);
  59831. effect.setTexture("textureSampler", _this._shadowMap);
  59832. });
  59833. this._boxBlurPostprocess.autoClear = false;
  59834. this._blurPostProcesses = [this._boxBlurPostprocess];
  59835. }
  59836. };
  59837. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59838. var index;
  59839. var engine = this._scene.getEngine();
  59840. if (depthOnlySubMeshes.length) {
  59841. engine.setColorWrite(false);
  59842. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59843. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59844. }
  59845. engine.setColorWrite(true);
  59846. }
  59847. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59848. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59849. }
  59850. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59851. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59852. }
  59853. if (this._transparencyShadow) {
  59854. for (index = 0; index < transparentSubMeshes.length; index++) {
  59855. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59856. }
  59857. }
  59858. };
  59859. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59860. var _this = this;
  59861. var mesh = subMesh.getRenderingMesh();
  59862. var scene = this._scene;
  59863. var engine = scene.getEngine();
  59864. var material = subMesh.getMaterial();
  59865. if (!material) {
  59866. return;
  59867. }
  59868. // Culling
  59869. engine.setState(material.backFaceCulling);
  59870. // Managing instances
  59871. var batch = mesh._getInstancesRenderList(subMesh._id);
  59872. if (batch.mustReturn) {
  59873. return;
  59874. }
  59875. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59876. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59877. engine.enableEffect(this._effect);
  59878. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59879. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59880. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59881. this._effect.setVector3("lightPosition", this.getLight().position);
  59882. if (scene.activeCamera) {
  59883. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59884. }
  59885. // Alpha test
  59886. if (material && material.needAlphaTesting()) {
  59887. var alphaTexture = material.getAlphaTestTexture();
  59888. if (alphaTexture) {
  59889. this._effect.setTexture("diffuseSampler", alphaTexture);
  59890. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59891. }
  59892. }
  59893. // Bones
  59894. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59895. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59896. }
  59897. if (this.forceBackFacesOnly) {
  59898. engine.setState(true, 0, false, true);
  59899. }
  59900. // Draw
  59901. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59902. if (this.forceBackFacesOnly) {
  59903. engine.setState(true, 0, false, false);
  59904. }
  59905. }
  59906. else {
  59907. // Need to reset refresh rate of the shadowMap
  59908. if (this._shadowMap) {
  59909. this._shadowMap.resetRefreshCounter();
  59910. }
  59911. }
  59912. };
  59913. ShadowGenerator.prototype._applyFilterValues = function () {
  59914. if (!this._shadowMap) {
  59915. return;
  59916. }
  59917. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59918. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59919. }
  59920. else {
  59921. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59922. }
  59923. };
  59924. /**
  59925. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59926. * @param onCompiled Callback triggered at the and of the effects compilation
  59927. * @param options Sets of optional options forcing the compilation with different modes
  59928. */
  59929. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59930. var _this = this;
  59931. var localOptions = __assign({ useInstances: false }, options);
  59932. var shadowMap = this.getShadowMap();
  59933. if (!shadowMap) {
  59934. if (onCompiled) {
  59935. onCompiled(this);
  59936. }
  59937. return;
  59938. }
  59939. var renderList = shadowMap.renderList;
  59940. if (!renderList) {
  59941. if (onCompiled) {
  59942. onCompiled(this);
  59943. }
  59944. return;
  59945. }
  59946. var subMeshes = new Array();
  59947. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59948. var mesh = renderList_1[_i];
  59949. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59950. }
  59951. if (subMeshes.length === 0) {
  59952. if (onCompiled) {
  59953. onCompiled(this);
  59954. }
  59955. return;
  59956. }
  59957. var currentIndex = 0;
  59958. var checkReady = function () {
  59959. if (!_this._scene || !_this._scene.getEngine()) {
  59960. return;
  59961. }
  59962. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59963. currentIndex++;
  59964. if (currentIndex >= subMeshes.length) {
  59965. if (onCompiled) {
  59966. onCompiled(_this);
  59967. }
  59968. return;
  59969. }
  59970. }
  59971. setTimeout(checkReady, 16);
  59972. };
  59973. checkReady();
  59974. };
  59975. /**
  59976. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59977. * @param options Sets of optional options forcing the compilation with different modes
  59978. * @returns A promise that resolves when the compilation completes
  59979. */
  59980. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59981. var _this = this;
  59982. return new Promise(function (resolve) {
  59983. _this.forceCompilation(function () {
  59984. resolve();
  59985. }, options);
  59986. });
  59987. };
  59988. /**
  59989. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59990. * @param subMesh The submesh we want to render in the shadow map
  59991. * @param useInstances Defines wether will draw in the map using instances
  59992. * @returns true if ready otherwise, false
  59993. */
  59994. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59995. var defines = [];
  59996. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59997. defines.push("#define FLOAT");
  59998. }
  59999. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60000. defines.push("#define ESM");
  60001. }
  60002. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60003. var mesh = subMesh.getMesh();
  60004. var material = subMesh.getMaterial();
  60005. // Alpha test
  60006. if (material && material.needAlphaTesting()) {
  60007. var alphaTexture = material.getAlphaTestTexture();
  60008. if (alphaTexture) {
  60009. defines.push("#define ALPHATEST");
  60010. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60011. attribs.push(BABYLON.VertexBuffer.UVKind);
  60012. defines.push("#define UV1");
  60013. }
  60014. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60015. if (alphaTexture.coordinatesIndex === 1) {
  60016. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60017. defines.push("#define UV2");
  60018. }
  60019. }
  60020. }
  60021. }
  60022. // Bones
  60023. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60024. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60025. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60026. if (mesh.numBoneInfluencers > 4) {
  60027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60029. }
  60030. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60031. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60032. }
  60033. else {
  60034. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60035. }
  60036. // Instances
  60037. if (useInstances) {
  60038. defines.push("#define INSTANCES");
  60039. attribs.push("world0");
  60040. attribs.push("world1");
  60041. attribs.push("world2");
  60042. attribs.push("world3");
  60043. }
  60044. // Get correct effect
  60045. var join = defines.join("\n");
  60046. if (this._cachedDefines !== join) {
  60047. this._cachedDefines = join;
  60048. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60049. }
  60050. if (!this._effect.isReady()) {
  60051. return false;
  60052. }
  60053. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60054. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60055. this._initializeBlurRTTAndPostProcesses();
  60056. }
  60057. }
  60058. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60059. return false;
  60060. }
  60061. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60062. return false;
  60063. }
  60064. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60065. return false;
  60066. }
  60067. return true;
  60068. };
  60069. /**
  60070. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60071. * @param defines Defines of the material we want to update
  60072. * @param lightIndex Index of the light in the enabled light list of the material
  60073. */
  60074. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60075. var scene = this._scene;
  60076. var light = this._light;
  60077. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60078. return;
  60079. }
  60080. defines["SHADOW" + lightIndex] = true;
  60081. if (this.usePoissonSampling) {
  60082. defines["SHADOWPCF" + lightIndex] = true;
  60083. }
  60084. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60085. defines["SHADOWESM" + lightIndex] = true;
  60086. }
  60087. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60088. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60089. }
  60090. if (light.needCube()) {
  60091. defines["SHADOWCUBE" + lightIndex] = true;
  60092. }
  60093. };
  60094. /**
  60095. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60096. * defined in the generator but impacting the effect).
  60097. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60098. * @param effect The effect we are binfing the information for
  60099. */
  60100. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60101. var light = this._light;
  60102. var scene = this._scene;
  60103. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60104. return;
  60105. }
  60106. var camera = scene.activeCamera;
  60107. if (!camera) {
  60108. return;
  60109. }
  60110. var shadowMap = this.getShadowMap();
  60111. if (!shadowMap) {
  60112. return;
  60113. }
  60114. if (!light.needCube()) {
  60115. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60116. }
  60117. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60118. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60119. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60120. };
  60121. /**
  60122. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60123. * (eq to shadow prjection matrix * light transform matrix)
  60124. * @returns The transform matrix used to create the shadow map
  60125. */
  60126. ShadowGenerator.prototype.getTransformMatrix = function () {
  60127. var scene = this._scene;
  60128. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60129. return this._transformMatrix;
  60130. }
  60131. this._currentRenderID = scene.getRenderId();
  60132. this._currentFaceIndexCache = this._currentFaceIndex;
  60133. var lightPosition = this._light.position;
  60134. if (this._light.computeTransformedInformation()) {
  60135. lightPosition = this._light.transformedPosition;
  60136. }
  60137. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60138. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60139. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60140. }
  60141. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60142. this._cachedPosition = lightPosition.clone();
  60143. this._cachedDirection = this._lightDirection.clone();
  60144. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60145. var shadowMap = this.getShadowMap();
  60146. if (shadowMap) {
  60147. var renderList = shadowMap.renderList;
  60148. if (renderList) {
  60149. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60150. }
  60151. }
  60152. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60153. }
  60154. return this._transformMatrix;
  60155. };
  60156. /**
  60157. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60158. * Cube and 2D textures for instance.
  60159. */
  60160. ShadowGenerator.prototype.recreateShadowMap = function () {
  60161. var shadowMap = this._shadowMap;
  60162. if (!shadowMap) {
  60163. return;
  60164. }
  60165. // Track render list.
  60166. var renderList = shadowMap.renderList;
  60167. // Clean up existing data.
  60168. this._disposeRTTandPostProcesses();
  60169. // Reinitializes.
  60170. this._initializeGenerator();
  60171. // Reaffect the filter to ensure a correct fallback if necessary.
  60172. this.filter = this.filter;
  60173. // Reaffect the filter.
  60174. this._applyFilterValues();
  60175. // Reaffect Render List.
  60176. this._shadowMap.renderList = renderList;
  60177. };
  60178. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60179. if (this._shadowMap2) {
  60180. this._shadowMap2.dispose();
  60181. this._shadowMap2 = null;
  60182. }
  60183. if (this._boxBlurPostprocess) {
  60184. this._boxBlurPostprocess.dispose();
  60185. this._boxBlurPostprocess = null;
  60186. }
  60187. if (this._kernelBlurXPostprocess) {
  60188. this._kernelBlurXPostprocess.dispose();
  60189. this._kernelBlurXPostprocess = null;
  60190. }
  60191. if (this._kernelBlurYPostprocess) {
  60192. this._kernelBlurYPostprocess.dispose();
  60193. this._kernelBlurYPostprocess = null;
  60194. }
  60195. this._blurPostProcesses = [];
  60196. };
  60197. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60198. if (this._shadowMap) {
  60199. this._shadowMap.dispose();
  60200. this._shadowMap = null;
  60201. }
  60202. this._disposeBlurPostProcesses();
  60203. };
  60204. /**
  60205. * Disposes the ShadowGenerator.
  60206. * Returns nothing.
  60207. */
  60208. ShadowGenerator.prototype.dispose = function () {
  60209. this._disposeRTTandPostProcesses();
  60210. if (this._light) {
  60211. this._light._shadowGenerator = null;
  60212. this._light._markMeshesAsLightDirty();
  60213. }
  60214. };
  60215. /**
  60216. * Serializes the shadow generator setup to a json object.
  60217. * @returns The serialized JSON object
  60218. */
  60219. ShadowGenerator.prototype.serialize = function () {
  60220. var serializationObject = {};
  60221. var shadowMap = this.getShadowMap();
  60222. if (!shadowMap) {
  60223. return serializationObject;
  60224. }
  60225. serializationObject.lightId = this._light.id;
  60226. serializationObject.mapSize = shadowMap.getRenderSize();
  60227. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60228. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60229. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60230. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60231. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60232. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60233. serializationObject.depthScale = this.depthScale;
  60234. serializationObject.darkness = this.getDarkness();
  60235. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60236. serializationObject.blurKernel = this.blurKernel;
  60237. serializationObject.blurScale = this.blurScale;
  60238. serializationObject.useKernelBlur = this.useKernelBlur;
  60239. serializationObject.transparencyShadow = this._transparencyShadow;
  60240. serializationObject.renderList = [];
  60241. if (shadowMap.renderList) {
  60242. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60243. var mesh = shadowMap.renderList[meshIndex];
  60244. serializationObject.renderList.push(mesh.id);
  60245. }
  60246. }
  60247. return serializationObject;
  60248. };
  60249. /**
  60250. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60251. * @param parsedShadowGenerator The JSON object to parse
  60252. * @param scene The scene to create the shadow map for
  60253. * @returns The parsed shadow generator
  60254. */
  60255. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60256. //casting to point light, as light is missing the position attr and typescript complains.
  60257. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60258. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60259. var shadowMap = shadowGenerator.getShadowMap();
  60260. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60261. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60262. meshes.forEach(function (mesh) {
  60263. if (!shadowMap) {
  60264. return;
  60265. }
  60266. if (!shadowMap.renderList) {
  60267. shadowMap.renderList = [];
  60268. }
  60269. shadowMap.renderList.push(mesh);
  60270. });
  60271. }
  60272. if (parsedShadowGenerator.usePoissonSampling) {
  60273. shadowGenerator.usePoissonSampling = true;
  60274. }
  60275. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60276. shadowGenerator.useExponentialShadowMap = true;
  60277. }
  60278. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60279. shadowGenerator.useBlurExponentialShadowMap = true;
  60280. }
  60281. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60282. shadowGenerator.useCloseExponentialShadowMap = true;
  60283. }
  60284. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60285. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60286. }
  60287. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60288. shadowGenerator.useExponentialShadowMap = true;
  60289. }
  60290. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60291. shadowGenerator.useBlurExponentialShadowMap = true;
  60292. }
  60293. if (parsedShadowGenerator.depthScale) {
  60294. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60295. }
  60296. if (parsedShadowGenerator.blurScale) {
  60297. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60298. }
  60299. if (parsedShadowGenerator.blurBoxOffset) {
  60300. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60301. }
  60302. if (parsedShadowGenerator.useKernelBlur) {
  60303. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60304. }
  60305. if (parsedShadowGenerator.blurKernel) {
  60306. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60307. }
  60308. if (parsedShadowGenerator.bias !== undefined) {
  60309. shadowGenerator.bias = parsedShadowGenerator.bias;
  60310. }
  60311. if (parsedShadowGenerator.darkness) {
  60312. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60313. }
  60314. if (parsedShadowGenerator.transparencyShadow) {
  60315. shadowGenerator.setTransparencyShadow(true);
  60316. }
  60317. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60318. return shadowGenerator;
  60319. };
  60320. ShadowGenerator._FILTER_NONE = 0;
  60321. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60322. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60323. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60324. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60325. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60326. return ShadowGenerator;
  60327. }());
  60328. BABYLON.ShadowGenerator = ShadowGenerator;
  60329. })(BABYLON || (BABYLON = {}));
  60330. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60331. var BABYLON;
  60332. (function (BABYLON) {
  60333. var DefaultLoadingScreen = /** @class */ (function () {
  60334. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60335. if (_loadingText === void 0) { _loadingText = ""; }
  60336. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60337. var _this = this;
  60338. this._renderingCanvas = _renderingCanvas;
  60339. this._loadingText = _loadingText;
  60340. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60341. // Resize
  60342. this._resizeLoadingUI = function () {
  60343. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60344. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60345. if (!_this._loadingDiv) {
  60346. return;
  60347. }
  60348. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60349. _this._loadingDiv.style.left = canvasRect.left + "px";
  60350. _this._loadingDiv.style.top = canvasRect.top + "px";
  60351. _this._loadingDiv.style.width = canvasRect.width + "px";
  60352. _this._loadingDiv.style.height = canvasRect.height + "px";
  60353. };
  60354. }
  60355. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60356. if (this._loadingDiv) {
  60357. // Do not add a loading screen if there is already one
  60358. return;
  60359. }
  60360. this._loadingDiv = document.createElement("div");
  60361. this._loadingDiv.id = "babylonjsLoadingDiv";
  60362. this._loadingDiv.style.opacity = "0";
  60363. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60364. this._loadingDiv.style.pointerEvents = "none";
  60365. // Loading text
  60366. this._loadingTextDiv = document.createElement("div");
  60367. this._loadingTextDiv.style.position = "absolute";
  60368. this._loadingTextDiv.style.left = "0";
  60369. this._loadingTextDiv.style.top = "50%";
  60370. this._loadingTextDiv.style.marginTop = "80px";
  60371. this._loadingTextDiv.style.width = "100%";
  60372. this._loadingTextDiv.style.height = "20px";
  60373. this._loadingTextDiv.style.fontFamily = "Arial";
  60374. this._loadingTextDiv.style.fontSize = "14px";
  60375. this._loadingTextDiv.style.color = "white";
  60376. this._loadingTextDiv.style.textAlign = "center";
  60377. this._loadingTextDiv.innerHTML = "Loading";
  60378. this._loadingDiv.appendChild(this._loadingTextDiv);
  60379. //set the predefined text
  60380. this._loadingTextDiv.innerHTML = this._loadingText;
  60381. // Generating keyframes
  60382. var style = document.createElement('style');
  60383. style.type = 'text/css';
  60384. 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 }";
  60385. style.innerHTML = keyFrames;
  60386. document.getElementsByTagName('head')[0].appendChild(style);
  60387. // Loading img
  60388. var imgBack = new Image();
  60389. 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";
  60390. imgBack.style.position = "absolute";
  60391. imgBack.style.left = "50%";
  60392. imgBack.style.top = "50%";
  60393. imgBack.style.marginLeft = "-60px";
  60394. imgBack.style.marginTop = "-60px";
  60395. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60396. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60397. imgBack.style.transformOrigin = "50% 50%";
  60398. imgBack.style.webkitTransformOrigin = "50% 50%";
  60399. this._loadingDiv.appendChild(imgBack);
  60400. this._resizeLoadingUI();
  60401. window.addEventListener("resize", this._resizeLoadingUI);
  60402. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60403. document.body.appendChild(this._loadingDiv);
  60404. this._loadingDiv.style.opacity = "1";
  60405. };
  60406. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60407. var _this = this;
  60408. if (!this._loadingDiv) {
  60409. return;
  60410. }
  60411. var onTransitionEnd = function () {
  60412. if (!_this._loadingDiv) {
  60413. return;
  60414. }
  60415. document.body.removeChild(_this._loadingDiv);
  60416. window.removeEventListener("resize", _this._resizeLoadingUI);
  60417. _this._loadingDiv = null;
  60418. };
  60419. this._loadingDiv.style.opacity = "0";
  60420. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60421. };
  60422. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60423. set: function (text) {
  60424. this._loadingText = text;
  60425. if (this._loadingTextDiv) {
  60426. this._loadingTextDiv.innerHTML = this._loadingText;
  60427. }
  60428. },
  60429. enumerable: true,
  60430. configurable: true
  60431. });
  60432. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60433. get: function () {
  60434. return this._loadingDivBackgroundColor;
  60435. },
  60436. set: function (color) {
  60437. this._loadingDivBackgroundColor = color;
  60438. if (!this._loadingDiv) {
  60439. return;
  60440. }
  60441. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60442. },
  60443. enumerable: true,
  60444. configurable: true
  60445. });
  60446. return DefaultLoadingScreen;
  60447. }());
  60448. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60449. })(BABYLON || (BABYLON = {}));
  60450. //# sourceMappingURL=babylon.loadingScreen.js.map
  60451. var BABYLON;
  60452. (function (BABYLON) {
  60453. var SceneLoaderProgressEvent = /** @class */ (function () {
  60454. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60455. this.lengthComputable = lengthComputable;
  60456. this.loaded = loaded;
  60457. this.total = total;
  60458. }
  60459. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60460. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60461. };
  60462. return SceneLoaderProgressEvent;
  60463. }());
  60464. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60465. var SceneLoader = /** @class */ (function () {
  60466. function SceneLoader() {
  60467. }
  60468. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60469. get: function () {
  60470. return 0;
  60471. },
  60472. enumerable: true,
  60473. configurable: true
  60474. });
  60475. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60476. get: function () {
  60477. return 1;
  60478. },
  60479. enumerable: true,
  60480. configurable: true
  60481. });
  60482. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60483. get: function () {
  60484. return 2;
  60485. },
  60486. enumerable: true,
  60487. configurable: true
  60488. });
  60489. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60490. get: function () {
  60491. return 3;
  60492. },
  60493. enumerable: true,
  60494. configurable: true
  60495. });
  60496. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60497. get: function () {
  60498. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60499. },
  60500. set: function (value) {
  60501. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60502. },
  60503. enumerable: true,
  60504. configurable: true
  60505. });
  60506. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60507. get: function () {
  60508. return SceneLoader._ShowLoadingScreen;
  60509. },
  60510. set: function (value) {
  60511. SceneLoader._ShowLoadingScreen = value;
  60512. },
  60513. enumerable: true,
  60514. configurable: true
  60515. });
  60516. Object.defineProperty(SceneLoader, "loggingLevel", {
  60517. get: function () {
  60518. return SceneLoader._loggingLevel;
  60519. },
  60520. set: function (value) {
  60521. SceneLoader._loggingLevel = value;
  60522. },
  60523. enumerable: true,
  60524. configurable: true
  60525. });
  60526. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60527. get: function () {
  60528. return SceneLoader._CleanBoneMatrixWeights;
  60529. },
  60530. set: function (value) {
  60531. SceneLoader._CleanBoneMatrixWeights = value;
  60532. },
  60533. enumerable: true,
  60534. configurable: true
  60535. });
  60536. SceneLoader._getDefaultPlugin = function () {
  60537. return SceneLoader._registeredPlugins[".babylon"];
  60538. };
  60539. SceneLoader._getPluginForExtension = function (extension) {
  60540. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60541. if (registeredPlugin) {
  60542. return registeredPlugin;
  60543. }
  60544. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60545. return SceneLoader._getDefaultPlugin();
  60546. };
  60547. SceneLoader._getPluginForDirectLoad = function (data) {
  60548. for (var extension in SceneLoader._registeredPlugins) {
  60549. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60550. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60551. return SceneLoader._registeredPlugins[extension];
  60552. }
  60553. }
  60554. return SceneLoader._getDefaultPlugin();
  60555. };
  60556. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60557. if (sceneFilename.name) {
  60558. sceneFilename = sceneFilename.name;
  60559. }
  60560. var queryStringPosition = sceneFilename.indexOf("?");
  60561. if (queryStringPosition !== -1) {
  60562. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60563. }
  60564. var dotPosition = sceneFilename.lastIndexOf(".");
  60565. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60566. return SceneLoader._getPluginForExtension(extension);
  60567. };
  60568. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60569. SceneLoader._getDirectLoad = function (sceneFilename) {
  60570. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60571. return sceneFilename.substr(5);
  60572. }
  60573. return null;
  60574. };
  60575. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60576. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60577. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60578. var plugin;
  60579. if (registeredPlugin.plugin.createPlugin) {
  60580. plugin = registeredPlugin.plugin.createPlugin();
  60581. }
  60582. else {
  60583. plugin = registeredPlugin.plugin;
  60584. }
  60585. var useArrayBuffer = registeredPlugin.isBinary;
  60586. var database;
  60587. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60588. var dataCallback = function (data, responseURL) {
  60589. if (scene.isDisposed) {
  60590. onError("Scene has been disposed");
  60591. return;
  60592. }
  60593. scene.database = database;
  60594. onSuccess(plugin, data, responseURL);
  60595. };
  60596. var request = null;
  60597. var pluginDisposed = false;
  60598. var onDisposeObservable = plugin.onDisposeObservable;
  60599. if (onDisposeObservable) {
  60600. onDisposeObservable.add(function () {
  60601. pluginDisposed = true;
  60602. if (request) {
  60603. request.abort();
  60604. request = null;
  60605. }
  60606. onDispose();
  60607. });
  60608. }
  60609. var manifestChecked = function () {
  60610. if (pluginDisposed) {
  60611. return;
  60612. }
  60613. var url = rootUrl + sceneFilename;
  60614. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60615. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60616. } : undefined, database, useArrayBuffer, function (request, exception) {
  60617. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60618. });
  60619. };
  60620. if (directLoad) {
  60621. dataCallback(directLoad);
  60622. return plugin;
  60623. }
  60624. if (rootUrl.indexOf("file:") === -1) {
  60625. if (scene.getEngine().enableOfflineSupport) {
  60626. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60627. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60628. }
  60629. else {
  60630. manifestChecked();
  60631. }
  60632. }
  60633. else {
  60634. var fileOrString = sceneFilename;
  60635. if (fileOrString.name) {
  60636. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60637. }
  60638. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60639. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60640. }
  60641. else {
  60642. onError("Unable to find file named " + sceneFilename);
  60643. }
  60644. }
  60645. return plugin;
  60646. };
  60647. // Public functions
  60648. SceneLoader.GetPluginForExtension = function (extension) {
  60649. return SceneLoader._getPluginForExtension(extension).plugin;
  60650. };
  60651. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60652. return !!SceneLoader._registeredPlugins[extension];
  60653. };
  60654. SceneLoader.RegisterPlugin = function (plugin) {
  60655. if (typeof plugin.extensions === "string") {
  60656. var extension = plugin.extensions;
  60657. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60658. plugin: plugin,
  60659. isBinary: false
  60660. };
  60661. }
  60662. else {
  60663. var extensions = plugin.extensions;
  60664. Object.keys(extensions).forEach(function (extension) {
  60665. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60666. plugin: plugin,
  60667. isBinary: extensions[extension].isBinary
  60668. };
  60669. });
  60670. }
  60671. };
  60672. /**
  60673. * Import meshes into a scene
  60674. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60675. * @param rootUrl a string that defines the root url for scene and resources
  60676. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60677. * @param scene the instance of BABYLON.Scene to append to
  60678. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60679. * @param onProgress a callback with a progress event for each file being loaded
  60680. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60681. * @param pluginExtension the extension used to determine the plugin
  60682. * @returns The loaded plugin
  60683. */
  60684. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60685. if (onSuccess === void 0) { onSuccess = null; }
  60686. if (onProgress === void 0) { onProgress = null; }
  60687. if (onError === void 0) { onError = null; }
  60688. if (pluginExtension === void 0) { pluginExtension = null; }
  60689. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60690. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60691. return null;
  60692. }
  60693. var loadingToken = {};
  60694. scene._addPendingData(loadingToken);
  60695. var disposeHandler = function () {
  60696. scene._removePendingData(loadingToken);
  60697. };
  60698. var errorHandler = function (message, exception) {
  60699. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60700. if (onError) {
  60701. onError(scene, errorMessage, exception);
  60702. }
  60703. else {
  60704. BABYLON.Tools.Error(errorMessage);
  60705. // should the exception be thrown?
  60706. }
  60707. disposeHandler();
  60708. };
  60709. var progressHandler = onProgress ? function (event) {
  60710. try {
  60711. onProgress(event);
  60712. }
  60713. catch (e) {
  60714. errorHandler("Error in onProgress callback", e);
  60715. }
  60716. } : undefined;
  60717. var successHandler = function (meshes, particleSystems, skeletons) {
  60718. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60719. if (onSuccess) {
  60720. try {
  60721. onSuccess(meshes, particleSystems, skeletons);
  60722. }
  60723. catch (e) {
  60724. errorHandler("Error in onSuccess callback", e);
  60725. }
  60726. }
  60727. scene._removePendingData(loadingToken);
  60728. };
  60729. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60730. if (plugin.rewriteRootURL) {
  60731. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60732. }
  60733. if (sceneFilename === "") {
  60734. if (sceneFilename === "") {
  60735. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60736. }
  60737. }
  60738. if (plugin.importMesh) {
  60739. var syncedPlugin = plugin;
  60740. var meshes = new Array();
  60741. var particleSystems = new Array();
  60742. var skeletons = new Array();
  60743. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60744. return;
  60745. }
  60746. scene.loadingPluginName = plugin.name;
  60747. successHandler(meshes, particleSystems, skeletons);
  60748. }
  60749. else {
  60750. var asyncedPlugin = plugin;
  60751. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60752. scene.loadingPluginName = plugin.name;
  60753. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60754. }).catch(function (error) {
  60755. errorHandler(error.message, error);
  60756. });
  60757. }
  60758. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60759. };
  60760. /**
  60761. * Import meshes into a scene
  60762. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60763. * @param rootUrl a string that defines the root url for scene and resources
  60764. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60765. * @param scene the instance of BABYLON.Scene to append to
  60766. * @param onProgress a callback with a progress event for each file being loaded
  60767. * @param pluginExtension the extension used to determine the plugin
  60768. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60769. */
  60770. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60771. if (onProgress === void 0) { onProgress = null; }
  60772. if (pluginExtension === void 0) { pluginExtension = null; }
  60773. return new Promise(function (resolve, reject) {
  60774. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60775. resolve({
  60776. meshes: meshes,
  60777. particleSystems: particleSystems,
  60778. skeletons: skeletons
  60779. });
  60780. }, onProgress, function (scene, message, exception) {
  60781. reject(exception || new Error(message));
  60782. });
  60783. });
  60784. };
  60785. /**
  60786. * Load a scene
  60787. * @param rootUrl a string that defines the root url for scene and resources
  60788. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60789. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60790. * @param onSuccess a callback with the scene when import succeeds
  60791. * @param onProgress a callback with a progress event for each file being loaded
  60792. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60793. * @param pluginExtension the extension used to determine the plugin
  60794. * @returns The loaded plugin
  60795. */
  60796. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60797. if (onSuccess === void 0) { onSuccess = null; }
  60798. if (onProgress === void 0) { onProgress = null; }
  60799. if (onError === void 0) { onError = null; }
  60800. if (pluginExtension === void 0) { pluginExtension = null; }
  60801. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60802. };
  60803. /**
  60804. * Load a scene
  60805. * @param rootUrl a string that defines the root url for scene and resources
  60806. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60807. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60808. * @param onProgress a callback with a progress event for each file being loaded
  60809. * @param pluginExtension the extension used to determine the plugin
  60810. * @returns The loaded scene
  60811. */
  60812. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60813. if (onProgress === void 0) { onProgress = null; }
  60814. if (pluginExtension === void 0) { pluginExtension = null; }
  60815. return new Promise(function (resolve, reject) {
  60816. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60817. resolve(scene);
  60818. }, onProgress, function (scene, message, exception) {
  60819. reject(exception || new Error(message));
  60820. }, pluginExtension);
  60821. });
  60822. };
  60823. /**
  60824. * Append a scene
  60825. * @param rootUrl a string that defines the root url for scene and resources
  60826. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60827. * @param scene is the instance of BABYLON.Scene to append to
  60828. * @param onSuccess a callback with the scene when import succeeds
  60829. * @param onProgress a callback with a progress event for each file being loaded
  60830. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60831. * @param pluginExtension the extension used to determine the plugin
  60832. * @returns The loaded plugin
  60833. */
  60834. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60835. if (onSuccess === void 0) { onSuccess = null; }
  60836. if (onProgress === void 0) { onProgress = null; }
  60837. if (onError === void 0) { onError = null; }
  60838. if (pluginExtension === void 0) { pluginExtension = null; }
  60839. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60840. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60841. return null;
  60842. }
  60843. if (SceneLoader.ShowLoadingScreen) {
  60844. scene.getEngine().displayLoadingUI();
  60845. }
  60846. var loadingToken = {};
  60847. scene._addPendingData(loadingToken);
  60848. var disposeHandler = function () {
  60849. scene._removePendingData(loadingToken);
  60850. scene.getEngine().hideLoadingUI();
  60851. };
  60852. var errorHandler = function (message, exception) {
  60853. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60854. if (onError) {
  60855. onError(scene, errorMessage, exception);
  60856. }
  60857. else {
  60858. BABYLON.Tools.Error(errorMessage);
  60859. // should the exception be thrown?
  60860. }
  60861. disposeHandler();
  60862. };
  60863. var progressHandler = onProgress ? function (event) {
  60864. try {
  60865. onProgress(event);
  60866. }
  60867. catch (e) {
  60868. errorHandler("Error in onProgress callback", e);
  60869. }
  60870. } : undefined;
  60871. var successHandler = function () {
  60872. if (onSuccess) {
  60873. try {
  60874. onSuccess(scene);
  60875. }
  60876. catch (e) {
  60877. errorHandler("Error in onSuccess callback", e);
  60878. }
  60879. }
  60880. scene._removePendingData(loadingToken);
  60881. };
  60882. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60883. if (sceneFilename === "") {
  60884. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60885. }
  60886. if (plugin.load) {
  60887. var syncedPlugin = plugin;
  60888. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60889. return;
  60890. }
  60891. scene.loadingPluginName = plugin.name;
  60892. successHandler();
  60893. }
  60894. else {
  60895. var asyncedPlugin = plugin;
  60896. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60897. scene.loadingPluginName = plugin.name;
  60898. successHandler();
  60899. }).catch(function (error) {
  60900. errorHandler(error.message, error);
  60901. });
  60902. }
  60903. if (SceneLoader.ShowLoadingScreen) {
  60904. scene.executeWhenReady(function () {
  60905. scene.getEngine().hideLoadingUI();
  60906. });
  60907. }
  60908. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60909. };
  60910. /**
  60911. * Append a scene
  60912. * @param rootUrl a string that defines the root url for scene and resources
  60913. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60914. * @param scene is the instance of BABYLON.Scene to append to
  60915. * @param onProgress a callback with a progress event for each file being loaded
  60916. * @param pluginExtension the extension used to determine the plugin
  60917. * @returns The given scene
  60918. */
  60919. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60920. if (onProgress === void 0) { onProgress = null; }
  60921. if (pluginExtension === void 0) { pluginExtension = null; }
  60922. return new Promise(function (resolve, reject) {
  60923. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60924. resolve(scene);
  60925. }, onProgress, function (scene, message, exception) {
  60926. reject(exception || new Error(message));
  60927. }, pluginExtension);
  60928. });
  60929. };
  60930. /**
  60931. * Load a scene into an asset container
  60932. * @param rootUrl a string that defines the root url for scene and resources
  60933. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60934. * @param scene is the instance of BABYLON.Scene to append to
  60935. * @param onSuccess a callback with the scene when import succeeds
  60936. * @param onProgress a callback with a progress event for each file being loaded
  60937. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60938. * @param pluginExtension the extension used to determine the plugin
  60939. * @returns The loaded plugin
  60940. */
  60941. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60942. if (onSuccess === void 0) { onSuccess = null; }
  60943. if (onProgress === void 0) { onProgress = null; }
  60944. if (onError === void 0) { onError = null; }
  60945. if (pluginExtension === void 0) { pluginExtension = null; }
  60946. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60947. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60948. return null;
  60949. }
  60950. var loadingToken = {};
  60951. scene._addPendingData(loadingToken);
  60952. var disposeHandler = function () {
  60953. scene._removePendingData(loadingToken);
  60954. };
  60955. var errorHandler = function (message, exception) {
  60956. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60957. if (onError) {
  60958. onError(scene, errorMessage, exception);
  60959. }
  60960. else {
  60961. BABYLON.Tools.Error(errorMessage);
  60962. // should the exception be thrown?
  60963. }
  60964. disposeHandler();
  60965. };
  60966. var progressHandler = onProgress ? function (event) {
  60967. try {
  60968. onProgress(event);
  60969. }
  60970. catch (e) {
  60971. errorHandler("Error in onProgress callback", e);
  60972. }
  60973. } : undefined;
  60974. var successHandler = function (assets) {
  60975. if (onSuccess) {
  60976. try {
  60977. onSuccess(assets);
  60978. }
  60979. catch (e) {
  60980. errorHandler("Error in onSuccess callback", e);
  60981. }
  60982. }
  60983. scene._removePendingData(loadingToken);
  60984. };
  60985. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60986. if (plugin.loadAssetContainer) {
  60987. var syncedPlugin = plugin;
  60988. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60989. if (!assetContainer) {
  60990. return;
  60991. }
  60992. scene.loadingPluginName = plugin.name;
  60993. successHandler(assetContainer);
  60994. }
  60995. else if (plugin.loadAssetContainerAsync) {
  60996. var asyncedPlugin = plugin;
  60997. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60998. scene.loadingPluginName = plugin.name;
  60999. successHandler(assetContainer);
  61000. }).catch(function (error) {
  61001. errorHandler(error.message, error);
  61002. });
  61003. }
  61004. else {
  61005. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61006. }
  61007. if (SceneLoader.ShowLoadingScreen) {
  61008. scene.executeWhenReady(function () {
  61009. scene.getEngine().hideLoadingUI();
  61010. });
  61011. }
  61012. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61013. };
  61014. /**
  61015. * Load a scene into an asset container
  61016. * @param rootUrl a string that defines the root url for scene and resources
  61017. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61018. * @param scene is the instance of BABYLON.Scene to append to
  61019. * @param onProgress a callback with a progress event for each file being loaded
  61020. * @param pluginExtension the extension used to determine the plugin
  61021. * @returns The loaded asset container
  61022. */
  61023. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61024. if (onProgress === void 0) { onProgress = null; }
  61025. if (pluginExtension === void 0) { pluginExtension = null; }
  61026. return new Promise(function (resolve, reject) {
  61027. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61028. resolve(assetContainer);
  61029. }, onProgress, function (scene, message, exception) {
  61030. reject(exception || new Error(message));
  61031. }, pluginExtension);
  61032. });
  61033. };
  61034. // Flags
  61035. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61036. SceneLoader._ShowLoadingScreen = true;
  61037. SceneLoader._CleanBoneMatrixWeights = false;
  61038. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61039. // Members
  61040. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61041. SceneLoader._registeredPlugins = {};
  61042. return SceneLoader;
  61043. }());
  61044. BABYLON.SceneLoader = SceneLoader;
  61045. ;
  61046. })(BABYLON || (BABYLON = {}));
  61047. //# sourceMappingURL=babylon.sceneLoader.js.map
  61048. var BABYLON;
  61049. (function (BABYLON) {
  61050. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61051. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61052. var parsedMaterial = parsedData.materials[index];
  61053. if (parsedMaterial.id === id) {
  61054. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61055. }
  61056. }
  61057. return null;
  61058. };
  61059. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61060. for (var i in names) {
  61061. if (mesh.name === names[i]) {
  61062. hierarchyIds.push(mesh.id);
  61063. return true;
  61064. }
  61065. }
  61066. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61067. hierarchyIds.push(mesh.id);
  61068. return true;
  61069. }
  61070. return false;
  61071. };
  61072. var logOperation = function (operation, producer) {
  61073. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61074. };
  61075. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61076. if (addToScene === void 0) { addToScene = false; }
  61077. var container = new BABYLON.AssetContainer(scene);
  61078. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61079. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61080. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61081. // and avoid problems with multiple concurrent .babylon loads.
  61082. var log = "importScene has failed JSON parse";
  61083. try {
  61084. var parsedData = JSON.parse(data);
  61085. log = "";
  61086. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61087. var index;
  61088. var cache;
  61089. // Lights
  61090. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61091. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61092. var parsedLight = parsedData.lights[index];
  61093. var light = BABYLON.Light.Parse(parsedLight, scene);
  61094. if (light) {
  61095. container.lights.push(light);
  61096. log += (index === 0 ? "\n\tLights:" : "");
  61097. log += "\n\t\t" + light.toString(fullDetails);
  61098. }
  61099. }
  61100. }
  61101. // Animations
  61102. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61103. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61104. var parsedAnimation = parsedData.animations[index];
  61105. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61106. scene.animations.push(animation);
  61107. container.animations.push(animation);
  61108. log += (index === 0 ? "\n\tAnimations:" : "");
  61109. log += "\n\t\t" + animation.toString(fullDetails);
  61110. }
  61111. }
  61112. // Materials
  61113. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61114. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61115. var parsedMaterial = parsedData.materials[index];
  61116. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61117. container.materials.push(mat);
  61118. log += (index === 0 ? "\n\tMaterials:" : "");
  61119. log += "\n\t\t" + mat.toString(fullDetails);
  61120. }
  61121. }
  61122. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61123. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61124. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61125. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61126. container.multiMaterials.push(mmat);
  61127. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61128. log += "\n\t\t" + mmat.toString(fullDetails);
  61129. }
  61130. }
  61131. // Morph targets
  61132. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61133. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61134. var managerData = _a[_i];
  61135. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61136. }
  61137. }
  61138. // Skeletons
  61139. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61140. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61141. var parsedSkeleton = parsedData.skeletons[index];
  61142. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61143. container.skeletons.push(skeleton);
  61144. log += (index === 0 ? "\n\tSkeletons:" : "");
  61145. log += "\n\t\t" + skeleton.toString(fullDetails);
  61146. }
  61147. }
  61148. // Geometries
  61149. var geometries = parsedData.geometries;
  61150. if (geometries !== undefined && geometries !== null) {
  61151. var addedGeometry = new Array();
  61152. // Boxes
  61153. var boxes = geometries.boxes;
  61154. if (boxes !== undefined && boxes !== null) {
  61155. for (index = 0, cache = boxes.length; index < cache; index++) {
  61156. var parsedBox = boxes[index];
  61157. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61158. }
  61159. }
  61160. // Spheres
  61161. var spheres = geometries.spheres;
  61162. if (spheres !== undefined && spheres !== null) {
  61163. for (index = 0, cache = spheres.length; index < cache; index++) {
  61164. var parsedSphere = spheres[index];
  61165. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61166. }
  61167. }
  61168. // Cylinders
  61169. var cylinders = geometries.cylinders;
  61170. if (cylinders !== undefined && cylinders !== null) {
  61171. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61172. var parsedCylinder = cylinders[index];
  61173. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61174. }
  61175. }
  61176. // Toruses
  61177. var toruses = geometries.toruses;
  61178. if (toruses !== undefined && toruses !== null) {
  61179. for (index = 0, cache = toruses.length; index < cache; index++) {
  61180. var parsedTorus = toruses[index];
  61181. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61182. }
  61183. }
  61184. // Grounds
  61185. var grounds = geometries.grounds;
  61186. if (grounds !== undefined && grounds !== null) {
  61187. for (index = 0, cache = grounds.length; index < cache; index++) {
  61188. var parsedGround = grounds[index];
  61189. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61190. }
  61191. }
  61192. // Planes
  61193. var planes = geometries.planes;
  61194. if (planes !== undefined && planes !== null) {
  61195. for (index = 0, cache = planes.length; index < cache; index++) {
  61196. var parsedPlane = planes[index];
  61197. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61198. }
  61199. }
  61200. // TorusKnots
  61201. var torusKnots = geometries.torusKnots;
  61202. if (torusKnots !== undefined && torusKnots !== null) {
  61203. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61204. var parsedTorusKnot = torusKnots[index];
  61205. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61206. }
  61207. }
  61208. // VertexData
  61209. var vertexData = geometries.vertexData;
  61210. if (vertexData !== undefined && vertexData !== null) {
  61211. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61212. var parsedVertexData = vertexData[index];
  61213. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61214. }
  61215. }
  61216. addedGeometry.forEach(function (g) {
  61217. if (g) {
  61218. container.geometries.push(g);
  61219. }
  61220. });
  61221. }
  61222. // Transform nodes
  61223. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61224. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61225. var parsedTransformNode = parsedData.transformNodes[index];
  61226. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61227. container.transformNodes.push(node);
  61228. }
  61229. }
  61230. // Meshes
  61231. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61232. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61233. var parsedMesh = parsedData.meshes[index];
  61234. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61235. container.meshes.push(mesh);
  61236. log += (index === 0 ? "\n\tMeshes:" : "");
  61237. log += "\n\t\t" + mesh.toString(fullDetails);
  61238. }
  61239. }
  61240. // Cameras
  61241. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61242. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61243. var parsedCamera = parsedData.cameras[index];
  61244. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61245. container.cameras.push(camera);
  61246. log += (index === 0 ? "\n\tCameras:" : "");
  61247. log += "\n\t\t" + camera.toString(fullDetails);
  61248. }
  61249. }
  61250. // Browsing all the graph to connect the dots
  61251. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61252. var camera = scene.cameras[index];
  61253. if (camera._waitingParentId) {
  61254. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61255. camera._waitingParentId = null;
  61256. }
  61257. }
  61258. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61259. var light_1 = scene.lights[index];
  61260. if (light_1 && light_1._waitingParentId) {
  61261. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61262. light_1._waitingParentId = null;
  61263. }
  61264. }
  61265. // Sounds
  61266. // TODO: add sound
  61267. var loadedSounds = [];
  61268. var loadedSound;
  61269. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61270. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61271. var parsedSound = parsedData.sounds[index];
  61272. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61273. if (!parsedSound.url)
  61274. parsedSound.url = parsedSound.name;
  61275. if (!loadedSounds[parsedSound.url]) {
  61276. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61277. loadedSounds[parsedSound.url] = loadedSound;
  61278. container.sounds.push(loadedSound);
  61279. }
  61280. else {
  61281. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61282. }
  61283. }
  61284. else {
  61285. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61286. }
  61287. }
  61288. }
  61289. loadedSounds = [];
  61290. // Connect parents & children and parse actions
  61291. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61292. var transformNode = scene.transformNodes[index];
  61293. if (transformNode._waitingParentId) {
  61294. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61295. transformNode._waitingParentId = null;
  61296. }
  61297. }
  61298. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61299. var mesh = scene.meshes[index];
  61300. if (mesh._waitingParentId) {
  61301. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61302. mesh._waitingParentId = null;
  61303. }
  61304. if (mesh._waitingActions) {
  61305. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61306. mesh._waitingActions = null;
  61307. }
  61308. }
  61309. // freeze world matrix application
  61310. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61311. var currentMesh = scene.meshes[index];
  61312. if (currentMesh._waitingFreezeWorldMatrix) {
  61313. currentMesh.freezeWorldMatrix();
  61314. currentMesh._waitingFreezeWorldMatrix = null;
  61315. }
  61316. else {
  61317. currentMesh.computeWorldMatrix(true);
  61318. }
  61319. }
  61320. // Particles Systems
  61321. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61322. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61323. var parsedParticleSystem = parsedData.particleSystems[index];
  61324. if (parsedParticleSystem.activeParticleCount) {
  61325. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61326. container.particleSystems.push(ps);
  61327. }
  61328. else {
  61329. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61330. container.particleSystems.push(ps);
  61331. }
  61332. }
  61333. }
  61334. // Lens flares
  61335. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61336. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61337. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61338. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61339. container.lensFlareSystems.push(lf);
  61340. }
  61341. }
  61342. // Shadows
  61343. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61344. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61345. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61346. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61347. container.shadowGenerators.push(sg);
  61348. }
  61349. }
  61350. // Lights exclusions / inclusions
  61351. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61352. var light_2 = scene.lights[index];
  61353. // Excluded check
  61354. if (light_2._excludedMeshesIds.length > 0) {
  61355. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61356. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61357. if (excludedMesh) {
  61358. light_2.excludedMeshes.push(excludedMesh);
  61359. }
  61360. }
  61361. light_2._excludedMeshesIds = [];
  61362. }
  61363. // Included check
  61364. if (light_2._includedOnlyMeshesIds.length > 0) {
  61365. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61366. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61367. if (includedOnlyMesh) {
  61368. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61369. }
  61370. }
  61371. light_2._includedOnlyMeshesIds = [];
  61372. }
  61373. }
  61374. // Actions (scene)
  61375. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61376. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61377. }
  61378. if (!addToScene) {
  61379. container.removeAllFromScene();
  61380. }
  61381. }
  61382. catch (err) {
  61383. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61384. if (onError) {
  61385. onError(msg, err);
  61386. }
  61387. else {
  61388. BABYLON.Tools.Log(msg);
  61389. throw err;
  61390. }
  61391. }
  61392. finally {
  61393. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61394. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61395. }
  61396. }
  61397. return container;
  61398. };
  61399. BABYLON.SceneLoader.RegisterPlugin({
  61400. name: "babylon.js",
  61401. extensions: ".babylon",
  61402. canDirectLoad: function (data) {
  61403. if (data.indexOf("babylon") !== -1) {
  61404. return true;
  61405. }
  61406. return false;
  61407. },
  61408. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61409. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61410. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61411. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61412. // and avoid problems with multiple concurrent .babylon loads.
  61413. var log = "importMesh has failed JSON parse";
  61414. try {
  61415. var parsedData = JSON.parse(data);
  61416. log = "";
  61417. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61418. if (!meshesNames) {
  61419. meshesNames = null;
  61420. }
  61421. else if (!Array.isArray(meshesNames)) {
  61422. meshesNames = [meshesNames];
  61423. }
  61424. var hierarchyIds = new Array();
  61425. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61426. var loadedSkeletonsIds = [];
  61427. var loadedMaterialsIds = [];
  61428. var index;
  61429. var cache;
  61430. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61431. var parsedMesh = parsedData.meshes[index];
  61432. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61433. if (meshesNames !== null) {
  61434. // Remove found mesh name from list.
  61435. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61436. }
  61437. //Geometry?
  61438. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61439. //does the file contain geometries?
  61440. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61441. //find the correct geometry and add it to the scene
  61442. var found = false;
  61443. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61444. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61445. return;
  61446. }
  61447. else {
  61448. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61449. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61450. switch (geometryType) {
  61451. case "boxes":
  61452. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61453. break;
  61454. case "spheres":
  61455. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61456. break;
  61457. case "cylinders":
  61458. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61459. break;
  61460. case "toruses":
  61461. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61462. break;
  61463. case "grounds":
  61464. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61465. break;
  61466. case "planes":
  61467. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61468. break;
  61469. case "torusKnots":
  61470. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61471. break;
  61472. case "vertexData":
  61473. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61474. break;
  61475. }
  61476. found = true;
  61477. }
  61478. });
  61479. }
  61480. });
  61481. if (found === false) {
  61482. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61483. }
  61484. }
  61485. }
  61486. // Material ?
  61487. if (parsedMesh.materialId) {
  61488. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61489. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61490. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61491. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61492. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61493. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61494. var subMatId = parsedMultiMaterial.materials[matIndex];
  61495. loadedMaterialsIds.push(subMatId);
  61496. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61497. if (mat) {
  61498. log += "\n\tMaterial " + mat.toString(fullDetails);
  61499. }
  61500. }
  61501. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61502. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61503. if (mmat) {
  61504. materialFound = true;
  61505. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61506. }
  61507. break;
  61508. }
  61509. }
  61510. }
  61511. if (materialFound === false) {
  61512. loadedMaterialsIds.push(parsedMesh.materialId);
  61513. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61514. if (!mat) {
  61515. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61516. }
  61517. else {
  61518. log += "\n\tMaterial " + mat.toString(fullDetails);
  61519. }
  61520. }
  61521. }
  61522. // Skeleton ?
  61523. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61524. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61525. if (skeletonAlreadyLoaded === false) {
  61526. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61527. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61528. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61529. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61530. skeletons.push(skeleton);
  61531. loadedSkeletonsIds.push(parsedSkeleton.id);
  61532. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61533. }
  61534. }
  61535. }
  61536. }
  61537. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61538. meshes.push(mesh);
  61539. log += "\n\tMesh " + mesh.toString(fullDetails);
  61540. }
  61541. }
  61542. // Connecting parents
  61543. var currentMesh;
  61544. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61545. currentMesh = scene.meshes[index];
  61546. if (currentMesh._waitingParentId) {
  61547. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61548. currentMesh._waitingParentId = null;
  61549. }
  61550. }
  61551. // freeze and compute world matrix application
  61552. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61553. currentMesh = scene.meshes[index];
  61554. if (currentMesh._waitingFreezeWorldMatrix) {
  61555. currentMesh.freezeWorldMatrix();
  61556. currentMesh._waitingFreezeWorldMatrix = null;
  61557. }
  61558. else {
  61559. currentMesh.computeWorldMatrix(true);
  61560. }
  61561. }
  61562. }
  61563. // Particles
  61564. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61565. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61566. var parsedParticleSystem = parsedData.particleSystems[index];
  61567. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61568. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61569. }
  61570. }
  61571. }
  61572. return true;
  61573. }
  61574. catch (err) {
  61575. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61576. if (onError) {
  61577. onError(msg, err);
  61578. }
  61579. else {
  61580. BABYLON.Tools.Log(msg);
  61581. throw err;
  61582. }
  61583. }
  61584. finally {
  61585. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61586. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61587. }
  61588. }
  61589. return false;
  61590. },
  61591. load: function (scene, data, rootUrl, onError) {
  61592. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61593. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61594. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61595. // and avoid problems with multiple concurrent .babylon loads.
  61596. var log = "importScene has failed JSON parse";
  61597. try {
  61598. var parsedData = JSON.parse(data);
  61599. log = "";
  61600. // Scene
  61601. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61602. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61603. }
  61604. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61605. scene.autoClear = parsedData.autoClear;
  61606. }
  61607. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61608. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61609. }
  61610. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61611. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61612. }
  61613. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61614. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61615. }
  61616. // Fog
  61617. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61618. scene.fogMode = parsedData.fogMode;
  61619. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61620. scene.fogStart = parsedData.fogStart;
  61621. scene.fogEnd = parsedData.fogEnd;
  61622. scene.fogDensity = parsedData.fogDensity;
  61623. log += "\tFog mode for scene: ";
  61624. switch (scene.fogMode) {
  61625. // getters not compiling, so using hardcoded
  61626. case 1:
  61627. log += "exp\n";
  61628. break;
  61629. case 2:
  61630. log += "exp2\n";
  61631. break;
  61632. case 3:
  61633. log += "linear\n";
  61634. break;
  61635. }
  61636. }
  61637. //Physics
  61638. if (parsedData.physicsEnabled) {
  61639. var physicsPlugin;
  61640. if (parsedData.physicsEngine === "cannon") {
  61641. physicsPlugin = new BABYLON.CannonJSPlugin();
  61642. }
  61643. else if (parsedData.physicsEngine === "oimo") {
  61644. physicsPlugin = new BABYLON.OimoJSPlugin();
  61645. }
  61646. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61647. //else - default engine, which is currently oimo
  61648. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61649. scene.enablePhysics(physicsGravity, physicsPlugin);
  61650. }
  61651. // Metadata
  61652. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61653. scene.metadata = parsedData.metadata;
  61654. }
  61655. //collisions, if defined. otherwise, default is true
  61656. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61657. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61658. }
  61659. scene.workerCollisions = !!parsedData.workerCollisions;
  61660. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61661. if (!container) {
  61662. return false;
  61663. }
  61664. if (parsedData.autoAnimate) {
  61665. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61666. }
  61667. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61668. scene.setActiveCameraByID(parsedData.activeCameraID);
  61669. }
  61670. // Environment texture
  61671. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61672. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61673. if (parsedData.createDefaultSkybox === true) {
  61674. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61675. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61676. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61677. }
  61678. }
  61679. // Finish
  61680. return true;
  61681. }
  61682. catch (err) {
  61683. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61684. if (onError) {
  61685. onError(msg, err);
  61686. }
  61687. else {
  61688. BABYLON.Tools.Log(msg);
  61689. throw err;
  61690. }
  61691. }
  61692. finally {
  61693. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61694. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61695. }
  61696. }
  61697. return false;
  61698. },
  61699. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61700. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61701. return container;
  61702. }
  61703. });
  61704. })(BABYLON || (BABYLON = {}));
  61705. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61706. var BABYLON;
  61707. (function (BABYLON) {
  61708. var FilesInput = /** @class */ (function () {
  61709. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61710. this.onProcessFileCallback = function () { return true; };
  61711. this._engine = engine;
  61712. this._currentScene = scene;
  61713. this._sceneLoadedCallback = sceneLoadedCallback;
  61714. this._progressCallback = progressCallback;
  61715. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61716. this._textureLoadingCallback = textureLoadingCallback;
  61717. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61718. this._onReloadCallback = onReloadCallback;
  61719. this._errorCallback = errorCallback;
  61720. }
  61721. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61722. var _this = this;
  61723. if (elementToMonitor) {
  61724. this._elementToMonitor = elementToMonitor;
  61725. this._dragEnterHandler = function (e) { _this.drag(e); };
  61726. this._dragOverHandler = function (e) { _this.drag(e); };
  61727. this._dropHandler = function (e) { _this.drop(e); };
  61728. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61729. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61730. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61731. }
  61732. };
  61733. FilesInput.prototype.dispose = function () {
  61734. if (!this._elementToMonitor) {
  61735. return;
  61736. }
  61737. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61738. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61739. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61740. };
  61741. FilesInput.prototype.renderFunction = function () {
  61742. if (this._additionalRenderLoopLogicCallback) {
  61743. this._additionalRenderLoopLogicCallback();
  61744. }
  61745. if (this._currentScene) {
  61746. if (this._textureLoadingCallback) {
  61747. var remaining = this._currentScene.getWaitingItemsCount();
  61748. if (remaining > 0) {
  61749. this._textureLoadingCallback(remaining);
  61750. }
  61751. }
  61752. this._currentScene.render();
  61753. }
  61754. };
  61755. FilesInput.prototype.drag = function (e) {
  61756. e.stopPropagation();
  61757. e.preventDefault();
  61758. };
  61759. FilesInput.prototype.drop = function (eventDrop) {
  61760. eventDrop.stopPropagation();
  61761. eventDrop.preventDefault();
  61762. this.loadFiles(eventDrop);
  61763. };
  61764. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61765. var _this = this;
  61766. var reader = folder.createReader();
  61767. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61768. reader.readEntries(function (entries) {
  61769. remaining.count += entries.length;
  61770. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61771. var entry = entries_1[_i];
  61772. if (entry.isFile) {
  61773. entry.file(function (file) {
  61774. file.correctName = relativePath + file.name;
  61775. files.push(file);
  61776. if (--remaining.count === 0) {
  61777. callback();
  61778. }
  61779. });
  61780. }
  61781. else if (entry.isDirectory) {
  61782. _this._traverseFolder(entry, files, remaining, callback);
  61783. }
  61784. }
  61785. if (--remaining.count) {
  61786. callback();
  61787. }
  61788. });
  61789. };
  61790. FilesInput.prototype._processFiles = function (files) {
  61791. for (var i = 0; i < files.length; i++) {
  61792. var name = files[i].correctName.toLowerCase();
  61793. var extension = name.split('.').pop();
  61794. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61795. continue;
  61796. }
  61797. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61798. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61799. this._sceneFileToLoad = files[i];
  61800. }
  61801. else {
  61802. FilesInput.FilesToLoad[name] = files[i];
  61803. }
  61804. }
  61805. };
  61806. FilesInput.prototype.loadFiles = function (event) {
  61807. var _this = this;
  61808. if (this._startingProcessingFilesCallback)
  61809. this._startingProcessingFilesCallback();
  61810. // Handling data transfer via drag'n'drop
  61811. if (event && event.dataTransfer && event.dataTransfer.files) {
  61812. this._filesToLoad = event.dataTransfer.files;
  61813. }
  61814. // Handling files from input files
  61815. if (event && event.target && event.target.files) {
  61816. this._filesToLoad = event.target.files;
  61817. }
  61818. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61819. var files_1 = new Array();
  61820. var folders = [];
  61821. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61822. for (var i = 0; i < this._filesToLoad.length; i++) {
  61823. var fileToLoad = this._filesToLoad[i];
  61824. var name_1 = fileToLoad.name.toLowerCase();
  61825. var entry = void 0;
  61826. fileToLoad.correctName = name_1;
  61827. if (items) {
  61828. var item = items[i];
  61829. if (item.getAsEntry) {
  61830. entry = item.getAsEntry();
  61831. }
  61832. else if (item.webkitGetAsEntry) {
  61833. entry = item.webkitGetAsEntry();
  61834. }
  61835. }
  61836. if (!entry) {
  61837. files_1.push(fileToLoad);
  61838. }
  61839. else {
  61840. if (entry.isDirectory) {
  61841. folders.push(entry);
  61842. }
  61843. else {
  61844. files_1.push(fileToLoad);
  61845. }
  61846. }
  61847. }
  61848. if (folders.length === 0) {
  61849. this._processFiles(files_1);
  61850. this._processReload();
  61851. }
  61852. else {
  61853. var remaining = { count: folders.length };
  61854. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61855. var folder = folders_1[_i];
  61856. this._traverseFolder(folder, files_1, remaining, function () {
  61857. _this._processFiles(files_1);
  61858. if (remaining.count === 0) {
  61859. _this._processReload();
  61860. }
  61861. });
  61862. }
  61863. }
  61864. }
  61865. };
  61866. FilesInput.prototype._processReload = function () {
  61867. if (this._onReloadCallback) {
  61868. this._onReloadCallback(this._sceneFileToLoad);
  61869. }
  61870. else {
  61871. this.reload();
  61872. }
  61873. };
  61874. FilesInput.prototype.reload = function () {
  61875. var _this = this;
  61876. // If a scene file has been provided
  61877. if (this._sceneFileToLoad) {
  61878. if (this._currentScene) {
  61879. if (BABYLON.Tools.errorsCount > 0) {
  61880. BABYLON.Tools.ClearLogCache();
  61881. }
  61882. this._engine.stopRenderLoop();
  61883. this._currentScene.dispose();
  61884. }
  61885. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61886. if (_this._progressCallback) {
  61887. _this._progressCallback(progress);
  61888. }
  61889. }).then(function (scene) {
  61890. _this._currentScene = scene;
  61891. if (_this._sceneLoadedCallback) {
  61892. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61893. }
  61894. // Wait for textures and shaders to be ready
  61895. _this._currentScene.executeWhenReady(function () {
  61896. _this._engine.runRenderLoop(function () {
  61897. _this.renderFunction();
  61898. });
  61899. });
  61900. }).catch(function (error) {
  61901. if (_this._errorCallback) {
  61902. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61903. }
  61904. });
  61905. }
  61906. else {
  61907. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61908. }
  61909. };
  61910. FilesInput.FilesToLoad = {};
  61911. return FilesInput;
  61912. }());
  61913. BABYLON.FilesInput = FilesInput;
  61914. })(BABYLON || (BABYLON = {}));
  61915. //# sourceMappingURL=babylon.filesInput.js.map
  61916. var BABYLON;
  61917. (function (BABYLON) {
  61918. /**
  61919. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61920. * The underlying implementation relies on an associative array to ensure the best performances.
  61921. * The value can be anything including 'null' but except 'undefined'
  61922. */
  61923. var StringDictionary = /** @class */ (function () {
  61924. function StringDictionary() {
  61925. this._count = 0;
  61926. this._data = {};
  61927. }
  61928. /**
  61929. * This will clear this dictionary and copy the content from the 'source' one.
  61930. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61931. * @param source the dictionary to take the content from and copy to this dictionary
  61932. */
  61933. StringDictionary.prototype.copyFrom = function (source) {
  61934. var _this = this;
  61935. this.clear();
  61936. source.forEach(function (t, v) { return _this.add(t, v); });
  61937. };
  61938. /**
  61939. * Get a value based from its key
  61940. * @param key the given key to get the matching value from
  61941. * @return the value if found, otherwise undefined is returned
  61942. */
  61943. StringDictionary.prototype.get = function (key) {
  61944. var val = this._data[key];
  61945. if (val !== undefined) {
  61946. return val;
  61947. }
  61948. return undefined;
  61949. };
  61950. /**
  61951. * Get a value from its key or add it if it doesn't exist.
  61952. * This method will ensure you that a given key/data will be present in the dictionary.
  61953. * @param key the given key to get the matching value from
  61954. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61955. * The factory will only be invoked if there's no data for the given key.
  61956. * @return the value corresponding to the key.
  61957. */
  61958. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61959. var val = this.get(key);
  61960. if (val !== undefined) {
  61961. return val;
  61962. }
  61963. val = factory(key);
  61964. if (val) {
  61965. this.add(key, val);
  61966. }
  61967. return val;
  61968. };
  61969. /**
  61970. * Get a value from its key if present in the dictionary otherwise add it
  61971. * @param key the key to get the value from
  61972. * @param val if there's no such key/value pair in the dictionary add it with this value
  61973. * @return the value corresponding to the key
  61974. */
  61975. StringDictionary.prototype.getOrAdd = function (key, val) {
  61976. var curVal = this.get(key);
  61977. if (curVal !== undefined) {
  61978. return curVal;
  61979. }
  61980. this.add(key, val);
  61981. return val;
  61982. };
  61983. /**
  61984. * Check if there's a given key in the dictionary
  61985. * @param key the key to check for
  61986. * @return true if the key is present, false otherwise
  61987. */
  61988. StringDictionary.prototype.contains = function (key) {
  61989. return this._data[key] !== undefined;
  61990. };
  61991. /**
  61992. * Add a new key and its corresponding value
  61993. * @param key the key to add
  61994. * @param value the value corresponding to the key
  61995. * @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
  61996. */
  61997. StringDictionary.prototype.add = function (key, value) {
  61998. if (this._data[key] !== undefined) {
  61999. return false;
  62000. }
  62001. this._data[key] = value;
  62002. ++this._count;
  62003. return true;
  62004. };
  62005. StringDictionary.prototype.set = function (key, value) {
  62006. if (this._data[key] === undefined) {
  62007. return false;
  62008. }
  62009. this._data[key] = value;
  62010. return true;
  62011. };
  62012. /**
  62013. * Get the element of the given key and remove it from the dictionary
  62014. * @param key
  62015. */
  62016. StringDictionary.prototype.getAndRemove = function (key) {
  62017. var val = this.get(key);
  62018. if (val !== undefined) {
  62019. delete this._data[key];
  62020. --this._count;
  62021. return val;
  62022. }
  62023. return null;
  62024. };
  62025. /**
  62026. * Remove a key/value from the dictionary.
  62027. * @param key the key to remove
  62028. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62029. */
  62030. StringDictionary.prototype.remove = function (key) {
  62031. if (this.contains(key)) {
  62032. delete this._data[key];
  62033. --this._count;
  62034. return true;
  62035. }
  62036. return false;
  62037. };
  62038. /**
  62039. * Clear the whole content of the dictionary
  62040. */
  62041. StringDictionary.prototype.clear = function () {
  62042. this._data = {};
  62043. this._count = 0;
  62044. };
  62045. Object.defineProperty(StringDictionary.prototype, "count", {
  62046. get: function () {
  62047. return this._count;
  62048. },
  62049. enumerable: true,
  62050. configurable: true
  62051. });
  62052. /**
  62053. * Execute a callback on each key/val of the dictionary.
  62054. * Note that you can remove any element in this dictionary in the callback implementation
  62055. * @param callback the callback to execute on a given key/value pair
  62056. */
  62057. StringDictionary.prototype.forEach = function (callback) {
  62058. for (var cur in this._data) {
  62059. var val = this._data[cur];
  62060. callback(cur, val);
  62061. }
  62062. };
  62063. /**
  62064. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62065. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62066. * Note that you can remove any element in this dictionary in the callback implementation
  62067. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62068. */
  62069. StringDictionary.prototype.first = function (callback) {
  62070. for (var cur in this._data) {
  62071. var val = this._data[cur];
  62072. var res = callback(cur, val);
  62073. if (res) {
  62074. return res;
  62075. }
  62076. }
  62077. return null;
  62078. };
  62079. return StringDictionary;
  62080. }());
  62081. BABYLON.StringDictionary = StringDictionary;
  62082. })(BABYLON || (BABYLON = {}));
  62083. //# sourceMappingURL=babylon.stringDictionary.js.map
  62084. var BABYLON;
  62085. (function (BABYLON) {
  62086. var Tags = /** @class */ (function () {
  62087. function Tags() {
  62088. }
  62089. Tags.EnableFor = function (obj) {
  62090. obj._tags = obj._tags || {};
  62091. obj.hasTags = function () {
  62092. return Tags.HasTags(obj);
  62093. };
  62094. obj.addTags = function (tagsString) {
  62095. return Tags.AddTagsTo(obj, tagsString);
  62096. };
  62097. obj.removeTags = function (tagsString) {
  62098. return Tags.RemoveTagsFrom(obj, tagsString);
  62099. };
  62100. obj.matchesTagsQuery = function (tagsQuery) {
  62101. return Tags.MatchesQuery(obj, tagsQuery);
  62102. };
  62103. };
  62104. Tags.DisableFor = function (obj) {
  62105. delete obj._tags;
  62106. delete obj.hasTags;
  62107. delete obj.addTags;
  62108. delete obj.removeTags;
  62109. delete obj.matchesTagsQuery;
  62110. };
  62111. Tags.HasTags = function (obj) {
  62112. if (!obj._tags) {
  62113. return false;
  62114. }
  62115. return !BABYLON.Tools.IsEmpty(obj._tags);
  62116. };
  62117. Tags.GetTags = function (obj, asString) {
  62118. if (asString === void 0) { asString = true; }
  62119. if (!obj._tags) {
  62120. return null;
  62121. }
  62122. if (asString) {
  62123. var tagsArray = [];
  62124. for (var tag in obj._tags) {
  62125. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62126. tagsArray.push(tag);
  62127. }
  62128. }
  62129. return tagsArray.join(" ");
  62130. }
  62131. else {
  62132. return obj._tags;
  62133. }
  62134. };
  62135. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62136. // a tag cannot start with '||', '&&', and '!'
  62137. // it cannot contain whitespaces
  62138. Tags.AddTagsTo = function (obj, tagsString) {
  62139. if (!tagsString) {
  62140. return;
  62141. }
  62142. if (typeof tagsString !== "string") {
  62143. return;
  62144. }
  62145. var tags = tagsString.split(" ");
  62146. tags.forEach(function (tag, index, array) {
  62147. Tags._AddTagTo(obj, tag);
  62148. });
  62149. };
  62150. Tags._AddTagTo = function (obj, tag) {
  62151. tag = tag.trim();
  62152. if (tag === "" || tag === "true" || tag === "false") {
  62153. return;
  62154. }
  62155. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62156. return;
  62157. }
  62158. Tags.EnableFor(obj);
  62159. obj._tags[tag] = true;
  62160. };
  62161. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62162. if (!Tags.HasTags(obj)) {
  62163. return;
  62164. }
  62165. var tags = tagsString.split(" ");
  62166. for (var t in tags) {
  62167. Tags._RemoveTagFrom(obj, tags[t]);
  62168. }
  62169. };
  62170. Tags._RemoveTagFrom = function (obj, tag) {
  62171. delete obj._tags[tag];
  62172. };
  62173. Tags.MatchesQuery = function (obj, tagsQuery) {
  62174. if (tagsQuery === undefined) {
  62175. return true;
  62176. }
  62177. if (tagsQuery === "") {
  62178. return Tags.HasTags(obj);
  62179. }
  62180. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62181. };
  62182. return Tags;
  62183. }());
  62184. BABYLON.Tags = Tags;
  62185. })(BABYLON || (BABYLON = {}));
  62186. //# sourceMappingURL=babylon.tags.js.map
  62187. var BABYLON;
  62188. (function (BABYLON) {
  62189. var AndOrNotEvaluator = /** @class */ (function () {
  62190. function AndOrNotEvaluator() {
  62191. }
  62192. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62193. if (!query.match(/\([^\(\)]*\)/g)) {
  62194. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62195. }
  62196. else {
  62197. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62198. // remove parenthesis
  62199. r = r.slice(1, r.length - 1);
  62200. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62201. });
  62202. }
  62203. if (query === "true") {
  62204. return true;
  62205. }
  62206. if (query === "false") {
  62207. return false;
  62208. }
  62209. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62210. };
  62211. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62212. evaluateCallback = evaluateCallback || (function (r) {
  62213. return r === "true" ? true : false;
  62214. });
  62215. var result;
  62216. var or = parenthesisContent.split("||");
  62217. for (var i in or) {
  62218. if (or.hasOwnProperty(i)) {
  62219. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62220. var and = ori.split("&&");
  62221. if (and.length > 1) {
  62222. for (var j = 0; j < and.length; ++j) {
  62223. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62224. if (andj !== "true" && andj !== "false") {
  62225. if (andj[0] === "!") {
  62226. result = !evaluateCallback(andj.substring(1));
  62227. }
  62228. else {
  62229. result = evaluateCallback(andj);
  62230. }
  62231. }
  62232. else {
  62233. result = andj === "true" ? true : false;
  62234. }
  62235. if (!result) {
  62236. ori = "false";
  62237. break;
  62238. }
  62239. }
  62240. }
  62241. if (result || ori === "true") {
  62242. result = true;
  62243. break;
  62244. }
  62245. // result equals false (or undefined)
  62246. if (ori !== "true" && ori !== "false") {
  62247. if (ori[0] === "!") {
  62248. result = !evaluateCallback(ori.substring(1));
  62249. }
  62250. else {
  62251. result = evaluateCallback(ori);
  62252. }
  62253. }
  62254. else {
  62255. result = ori === "true" ? true : false;
  62256. }
  62257. }
  62258. }
  62259. // the whole parenthesis scope is replaced by 'true' or 'false'
  62260. return result ? "true" : "false";
  62261. };
  62262. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62263. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62264. // remove whitespaces
  62265. r = r.replace(/[\s]/g, function () { return ""; });
  62266. return r.length % 2 ? "!" : "";
  62267. });
  62268. booleanString = booleanString.trim();
  62269. if (booleanString === "!true") {
  62270. booleanString = "false";
  62271. }
  62272. else if (booleanString === "!false") {
  62273. booleanString = "true";
  62274. }
  62275. return booleanString;
  62276. };
  62277. return AndOrNotEvaluator;
  62278. }());
  62279. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62280. })(BABYLON || (BABYLON = {}));
  62281. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62282. var BABYLON;
  62283. (function (BABYLON) {
  62284. var Database = /** @class */ (function () {
  62285. function Database(urlToScene, callbackManifestChecked) {
  62286. // Handling various flavors of prefixed version of IndexedDB
  62287. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62288. this.callbackManifestChecked = callbackManifestChecked;
  62289. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62290. this.db = null;
  62291. this._enableSceneOffline = false;
  62292. this._enableTexturesOffline = false;
  62293. this.manifestVersionFound = 0;
  62294. this.mustUpdateRessources = false;
  62295. this.hasReachedQuota = false;
  62296. if (!Database.IDBStorageEnabled) {
  62297. this.callbackManifestChecked(true);
  62298. }
  62299. else {
  62300. this.checkManifestFile();
  62301. }
  62302. }
  62303. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62304. get: function () {
  62305. return this._enableSceneOffline;
  62306. },
  62307. enumerable: true,
  62308. configurable: true
  62309. });
  62310. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62311. get: function () {
  62312. return this._enableTexturesOffline;
  62313. },
  62314. enumerable: true,
  62315. configurable: true
  62316. });
  62317. Database.prototype.checkManifestFile = function () {
  62318. var _this = this;
  62319. var noManifestFile = function () {
  62320. _this._enableSceneOffline = false;
  62321. _this._enableTexturesOffline = false;
  62322. _this.callbackManifestChecked(false);
  62323. };
  62324. var timeStampUsed = false;
  62325. var manifestURL = this.currentSceneUrl + ".manifest";
  62326. var xhr = new XMLHttpRequest();
  62327. if (navigator.onLine) {
  62328. // Adding a timestamp to by-pass browsers' cache
  62329. timeStampUsed = true;
  62330. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62331. }
  62332. xhr.open("GET", manifestURL, true);
  62333. xhr.addEventListener("load", function () {
  62334. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62335. try {
  62336. var manifestFile = JSON.parse(xhr.response);
  62337. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62338. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62339. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62340. _this.manifestVersionFound = manifestFile.version;
  62341. }
  62342. if (_this.callbackManifestChecked) {
  62343. _this.callbackManifestChecked(true);
  62344. }
  62345. }
  62346. catch (ex) {
  62347. noManifestFile();
  62348. }
  62349. }
  62350. else {
  62351. noManifestFile();
  62352. }
  62353. }, false);
  62354. xhr.addEventListener("error", function (event) {
  62355. if (timeStampUsed) {
  62356. timeStampUsed = false;
  62357. // Let's retry without the timeStamp
  62358. // It could fail when coupled with HTML5 Offline API
  62359. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62360. xhr.open("GET", retryManifestURL, true);
  62361. xhr.send();
  62362. }
  62363. else {
  62364. noManifestFile();
  62365. }
  62366. }, false);
  62367. try {
  62368. xhr.send();
  62369. }
  62370. catch (ex) {
  62371. BABYLON.Tools.Error("Error on XHR send request.");
  62372. this.callbackManifestChecked(false);
  62373. }
  62374. };
  62375. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62376. var _this = this;
  62377. var handleError = function () {
  62378. _this.isSupported = false;
  62379. if (errorCallback)
  62380. errorCallback();
  62381. };
  62382. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62383. // Your browser doesn't support IndexedDB
  62384. this.isSupported = false;
  62385. if (errorCallback)
  62386. errorCallback();
  62387. }
  62388. else {
  62389. // If the DB hasn't been opened or created yet
  62390. if (!this.db) {
  62391. this.hasReachedQuota = false;
  62392. this.isSupported = true;
  62393. var request = this.idbFactory.open("babylonjs", 1);
  62394. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62395. request.onerror = function (event) {
  62396. handleError();
  62397. };
  62398. // executes when a version change transaction cannot complete due to other active transactions
  62399. request.onblocked = function (event) {
  62400. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62401. handleError();
  62402. };
  62403. // DB has been opened successfully
  62404. request.onsuccess = function (event) {
  62405. _this.db = request.result;
  62406. successCallback();
  62407. };
  62408. // Initialization of the DB. Creating Scenes & Textures stores
  62409. request.onupgradeneeded = function (event) {
  62410. _this.db = (event.target).result;
  62411. if (_this.db) {
  62412. try {
  62413. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62414. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62415. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62416. }
  62417. catch (ex) {
  62418. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62419. handleError();
  62420. }
  62421. }
  62422. };
  62423. }
  62424. else {
  62425. if (successCallback)
  62426. successCallback();
  62427. }
  62428. }
  62429. };
  62430. Database.prototype.loadImageFromDB = function (url, image) {
  62431. var _this = this;
  62432. var completeURL = Database.ReturnFullUrlLocation(url);
  62433. var saveAndLoadImage = function () {
  62434. if (!_this.hasReachedQuota && _this.db !== null) {
  62435. // the texture is not yet in the DB, let's try to save it
  62436. _this._saveImageIntoDBAsync(completeURL, image);
  62437. }
  62438. else {
  62439. image.src = url;
  62440. }
  62441. };
  62442. if (!this.mustUpdateRessources) {
  62443. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62444. }
  62445. else {
  62446. saveAndLoadImage();
  62447. }
  62448. };
  62449. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62450. if (this.isSupported && this.db !== null) {
  62451. var texture;
  62452. var transaction = this.db.transaction(["textures"]);
  62453. transaction.onabort = function (event) {
  62454. image.src = url;
  62455. };
  62456. transaction.oncomplete = function (event) {
  62457. var blobTextureURL;
  62458. if (texture) {
  62459. var URL = window.URL || window.webkitURL;
  62460. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62461. image.onerror = function () {
  62462. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62463. image.src = url;
  62464. };
  62465. image.src = blobTextureURL;
  62466. }
  62467. else {
  62468. notInDBCallback();
  62469. }
  62470. };
  62471. var getRequest = transaction.objectStore("textures").get(url);
  62472. getRequest.onsuccess = function (event) {
  62473. texture = (event.target).result;
  62474. };
  62475. getRequest.onerror = function (event) {
  62476. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62477. image.src = url;
  62478. };
  62479. }
  62480. else {
  62481. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62482. image.src = url;
  62483. }
  62484. };
  62485. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62486. var _this = this;
  62487. if (this.isSupported) {
  62488. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62489. var generateBlobUrl = function () {
  62490. var blobTextureURL;
  62491. if (blob) {
  62492. var URL = window.URL || window.webkitURL;
  62493. try {
  62494. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62495. }
  62496. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62497. catch (ex) {
  62498. blobTextureURL = URL.createObjectURL(blob);
  62499. }
  62500. }
  62501. if (blobTextureURL) {
  62502. image.src = blobTextureURL;
  62503. }
  62504. };
  62505. if (Database.IsUASupportingBlobStorage) {
  62506. var xhr = new XMLHttpRequest(), blob;
  62507. xhr.open("GET", url, true);
  62508. xhr.responseType = "blob";
  62509. xhr.addEventListener("load", function () {
  62510. if (xhr.status === 200 && _this.db) {
  62511. // Blob as response (XHR2)
  62512. blob = xhr.response;
  62513. var transaction = _this.db.transaction(["textures"], "readwrite");
  62514. // the transaction could abort because of a QuotaExceededError error
  62515. transaction.onabort = function (event) {
  62516. try {
  62517. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62518. var srcElement = (event.srcElement || event.target);
  62519. var error = srcElement.error;
  62520. if (error && error.name === "QuotaExceededError") {
  62521. _this.hasReachedQuota = true;
  62522. }
  62523. }
  62524. catch (ex) { }
  62525. generateBlobUrl();
  62526. };
  62527. transaction.oncomplete = function (event) {
  62528. generateBlobUrl();
  62529. };
  62530. var newTexture = { textureUrl: url, data: blob };
  62531. try {
  62532. // Put the blob into the dabase
  62533. var addRequest = transaction.objectStore("textures").put(newTexture);
  62534. addRequest.onsuccess = function (event) {
  62535. };
  62536. addRequest.onerror = function (event) {
  62537. generateBlobUrl();
  62538. };
  62539. }
  62540. catch (ex) {
  62541. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62542. if (ex.code === 25) {
  62543. Database.IsUASupportingBlobStorage = false;
  62544. }
  62545. image.src = url;
  62546. }
  62547. }
  62548. else {
  62549. image.src = url;
  62550. }
  62551. }, false);
  62552. xhr.addEventListener("error", function (event) {
  62553. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62554. image.src = url;
  62555. }, false);
  62556. xhr.send();
  62557. }
  62558. else {
  62559. image.src = url;
  62560. }
  62561. }
  62562. else {
  62563. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62564. image.src = url;
  62565. }
  62566. };
  62567. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62568. var _this = this;
  62569. var updateVersion = function () {
  62570. // the version is not yet in the DB or we need to update it
  62571. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62572. };
  62573. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62574. };
  62575. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62576. var _this = this;
  62577. if (this.isSupported && this.db) {
  62578. var version;
  62579. try {
  62580. var transaction = this.db.transaction(["versions"]);
  62581. transaction.oncomplete = function (event) {
  62582. if (version) {
  62583. // If the version in the JSON file is > than the version in DB
  62584. if (_this.manifestVersionFound > version.data) {
  62585. _this.mustUpdateRessources = true;
  62586. updateInDBCallback();
  62587. }
  62588. else {
  62589. callback(version.data);
  62590. }
  62591. }
  62592. else {
  62593. _this.mustUpdateRessources = true;
  62594. updateInDBCallback();
  62595. }
  62596. };
  62597. transaction.onabort = function (event) {
  62598. callback(-1);
  62599. };
  62600. var getRequest = transaction.objectStore("versions").get(url);
  62601. getRequest.onsuccess = function (event) {
  62602. version = (event.target).result;
  62603. };
  62604. getRequest.onerror = function (event) {
  62605. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62606. callback(-1);
  62607. };
  62608. }
  62609. catch (ex) {
  62610. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62611. callback(-1);
  62612. }
  62613. }
  62614. else {
  62615. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62616. callback(-1);
  62617. }
  62618. };
  62619. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62620. var _this = this;
  62621. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62622. try {
  62623. // Open a transaction to the database
  62624. var transaction = this.db.transaction(["versions"], "readwrite");
  62625. // the transaction could abort because of a QuotaExceededError error
  62626. transaction.onabort = function (event) {
  62627. try {
  62628. var error = event.srcElement['error'];
  62629. if (error && error.name === "QuotaExceededError") {
  62630. _this.hasReachedQuota = true;
  62631. }
  62632. }
  62633. catch (ex) { }
  62634. callback(-1);
  62635. };
  62636. transaction.oncomplete = function (event) {
  62637. callback(_this.manifestVersionFound);
  62638. };
  62639. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62640. // Put the scene into the database
  62641. var addRequest = transaction.objectStore("versions").put(newVersion);
  62642. addRequest.onsuccess = function (event) {
  62643. };
  62644. addRequest.onerror = function (event) {
  62645. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62646. };
  62647. }
  62648. catch (ex) {
  62649. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62650. callback(-1);
  62651. }
  62652. }
  62653. else {
  62654. callback(-1);
  62655. }
  62656. };
  62657. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62658. var _this = this;
  62659. var completeUrl = Database.ReturnFullUrlLocation(url);
  62660. var saveAndLoadFile = function () {
  62661. // the scene is not yet in the DB, let's try to save it
  62662. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62663. };
  62664. this._checkVersionFromDB(completeUrl, function (version) {
  62665. if (version !== -1) {
  62666. if (!_this.mustUpdateRessources) {
  62667. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62668. }
  62669. else {
  62670. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62671. }
  62672. }
  62673. else {
  62674. if (errorCallback) {
  62675. errorCallback();
  62676. }
  62677. }
  62678. });
  62679. };
  62680. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62681. if (this.isSupported && this.db) {
  62682. var targetStore;
  62683. if (url.indexOf(".babylon") !== -1) {
  62684. targetStore = "scenes";
  62685. }
  62686. else {
  62687. targetStore = "textures";
  62688. }
  62689. var file;
  62690. var transaction = this.db.transaction([targetStore]);
  62691. transaction.oncomplete = function (event) {
  62692. if (file) {
  62693. callback(file.data);
  62694. }
  62695. else {
  62696. notInDBCallback();
  62697. }
  62698. };
  62699. transaction.onabort = function (event) {
  62700. notInDBCallback();
  62701. };
  62702. var getRequest = transaction.objectStore(targetStore).get(url);
  62703. getRequest.onsuccess = function (event) {
  62704. file = (event.target).result;
  62705. };
  62706. getRequest.onerror = function (event) {
  62707. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62708. notInDBCallback();
  62709. };
  62710. }
  62711. else {
  62712. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62713. callback();
  62714. }
  62715. };
  62716. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62717. var _this = this;
  62718. if (this.isSupported) {
  62719. var targetStore;
  62720. if (url.indexOf(".babylon") !== -1) {
  62721. targetStore = "scenes";
  62722. }
  62723. else {
  62724. targetStore = "textures";
  62725. }
  62726. // Create XHR
  62727. var xhr = new XMLHttpRequest();
  62728. var fileData;
  62729. xhr.open("GET", url, true);
  62730. if (useArrayBuffer) {
  62731. xhr.responseType = "arraybuffer";
  62732. }
  62733. if (progressCallback) {
  62734. xhr.onprogress = progressCallback;
  62735. }
  62736. xhr.addEventListener("load", function () {
  62737. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62738. // Blob as response (XHR2)
  62739. //fileData = xhr.responseText;
  62740. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62741. if (!_this.hasReachedQuota && _this.db) {
  62742. // Open a transaction to the database
  62743. var transaction = _this.db.transaction([targetStore], "readwrite");
  62744. // the transaction could abort because of a QuotaExceededError error
  62745. transaction.onabort = function (event) {
  62746. try {
  62747. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62748. var error = event.srcElement['error'];
  62749. if (error && error.name === "QuotaExceededError") {
  62750. _this.hasReachedQuota = true;
  62751. }
  62752. }
  62753. catch (ex) { }
  62754. callback(fileData);
  62755. };
  62756. transaction.oncomplete = function (event) {
  62757. callback(fileData);
  62758. };
  62759. var newFile;
  62760. if (targetStore === "scenes") {
  62761. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62762. }
  62763. else {
  62764. newFile = { textureUrl: url, data: fileData };
  62765. }
  62766. try {
  62767. // Put the scene into the database
  62768. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62769. addRequest.onsuccess = function (event) {
  62770. };
  62771. addRequest.onerror = function (event) {
  62772. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62773. };
  62774. }
  62775. catch (ex) {
  62776. callback(fileData);
  62777. }
  62778. }
  62779. else {
  62780. callback(fileData);
  62781. }
  62782. }
  62783. else {
  62784. callback();
  62785. }
  62786. }, false);
  62787. xhr.addEventListener("error", function (event) {
  62788. BABYLON.Tools.Error("error on XHR request.");
  62789. callback();
  62790. }, false);
  62791. xhr.send();
  62792. }
  62793. else {
  62794. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62795. callback();
  62796. }
  62797. };
  62798. Database.IsUASupportingBlobStorage = true;
  62799. Database.IDBStorageEnabled = true;
  62800. Database.parseURL = function (url) {
  62801. var a = document.createElement('a');
  62802. a.href = url;
  62803. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62804. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62805. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62806. return absLocation;
  62807. };
  62808. Database.ReturnFullUrlLocation = function (url) {
  62809. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62810. return (Database.parseURL(window.location.href) + url);
  62811. }
  62812. else {
  62813. return url;
  62814. }
  62815. };
  62816. return Database;
  62817. }());
  62818. BABYLON.Database = Database;
  62819. })(BABYLON || (BABYLON = {}));
  62820. //# sourceMappingURL=babylon.database.js.map
  62821. var BABYLON;
  62822. (function (BABYLON) {
  62823. var FresnelParameters = /** @class */ (function () {
  62824. function FresnelParameters() {
  62825. this._isEnabled = true;
  62826. this.leftColor = BABYLON.Color3.White();
  62827. this.rightColor = BABYLON.Color3.Black();
  62828. this.bias = 0;
  62829. this.power = 1;
  62830. }
  62831. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62832. get: function () {
  62833. return this._isEnabled;
  62834. },
  62835. set: function (value) {
  62836. if (this._isEnabled === value) {
  62837. return;
  62838. }
  62839. this._isEnabled = value;
  62840. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62841. },
  62842. enumerable: true,
  62843. configurable: true
  62844. });
  62845. FresnelParameters.prototype.clone = function () {
  62846. var newFresnelParameters = new FresnelParameters();
  62847. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62848. return newFresnelParameters;
  62849. };
  62850. FresnelParameters.prototype.serialize = function () {
  62851. var serializationObject = {};
  62852. serializationObject.isEnabled = this.isEnabled;
  62853. serializationObject.leftColor = this.leftColor;
  62854. serializationObject.rightColor = this.rightColor;
  62855. serializationObject.bias = this.bias;
  62856. serializationObject.power = this.power;
  62857. return serializationObject;
  62858. };
  62859. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62860. var fresnelParameters = new FresnelParameters();
  62861. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62862. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62863. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62864. fresnelParameters.bias = parsedFresnelParameters.bias;
  62865. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62866. return fresnelParameters;
  62867. };
  62868. return FresnelParameters;
  62869. }());
  62870. BABYLON.FresnelParameters = FresnelParameters;
  62871. })(BABYLON || (BABYLON = {}));
  62872. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62873. var BABYLON;
  62874. (function (BABYLON) {
  62875. var MultiMaterial = /** @class */ (function (_super) {
  62876. __extends(MultiMaterial, _super);
  62877. function MultiMaterial(name, scene) {
  62878. var _this = _super.call(this, name, scene, true) || this;
  62879. scene.multiMaterials.push(_this);
  62880. _this.subMaterials = new Array();
  62881. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62882. return _this;
  62883. }
  62884. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62885. get: function () {
  62886. return this._subMaterials;
  62887. },
  62888. set: function (value) {
  62889. this._subMaterials = value;
  62890. this._hookArray(value);
  62891. },
  62892. enumerable: true,
  62893. configurable: true
  62894. });
  62895. MultiMaterial.prototype._hookArray = function (array) {
  62896. var _this = this;
  62897. var oldPush = array.push;
  62898. array.push = function () {
  62899. var items = [];
  62900. for (var _i = 0; _i < arguments.length; _i++) {
  62901. items[_i] = arguments[_i];
  62902. }
  62903. var result = oldPush.apply(array, items);
  62904. _this._markAllSubMeshesAsTexturesDirty();
  62905. return result;
  62906. };
  62907. var oldSplice = array.splice;
  62908. array.splice = function (index, deleteCount) {
  62909. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62910. _this._markAllSubMeshesAsTexturesDirty();
  62911. return deleted;
  62912. };
  62913. };
  62914. // Properties
  62915. MultiMaterial.prototype.getSubMaterial = function (index) {
  62916. if (index < 0 || index >= this.subMaterials.length) {
  62917. return this.getScene().defaultMaterial;
  62918. }
  62919. return this.subMaterials[index];
  62920. };
  62921. MultiMaterial.prototype.getActiveTextures = function () {
  62922. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62923. if (subMaterial) {
  62924. return subMaterial.getActiveTextures();
  62925. }
  62926. else {
  62927. return [];
  62928. }
  62929. }));
  62930. var _a;
  62931. };
  62932. // Methods
  62933. MultiMaterial.prototype.getClassName = function () {
  62934. return "MultiMaterial";
  62935. };
  62936. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62937. for (var index = 0; index < this.subMaterials.length; index++) {
  62938. var subMaterial = this.subMaterials[index];
  62939. if (subMaterial) {
  62940. if (subMaterial.storeEffectOnSubMeshes) {
  62941. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62942. return false;
  62943. }
  62944. continue;
  62945. }
  62946. if (!subMaterial.isReady(mesh)) {
  62947. return false;
  62948. }
  62949. }
  62950. }
  62951. return true;
  62952. };
  62953. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62954. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62955. for (var index = 0; index < this.subMaterials.length; index++) {
  62956. var subMaterial = null;
  62957. var current = this.subMaterials[index];
  62958. if (cloneChildren && current) {
  62959. subMaterial = current.clone(name + "-" + current.name);
  62960. }
  62961. else {
  62962. subMaterial = this.subMaterials[index];
  62963. }
  62964. newMultiMaterial.subMaterials.push(subMaterial);
  62965. }
  62966. return newMultiMaterial;
  62967. };
  62968. MultiMaterial.prototype.serialize = function () {
  62969. var serializationObject = {};
  62970. serializationObject.name = this.name;
  62971. serializationObject.id = this.id;
  62972. if (BABYLON.Tags) {
  62973. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62974. }
  62975. serializationObject.materials = [];
  62976. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62977. var subMat = this.subMaterials[matIndex];
  62978. if (subMat) {
  62979. serializationObject.materials.push(subMat.id);
  62980. }
  62981. else {
  62982. serializationObject.materials.push(null);
  62983. }
  62984. }
  62985. return serializationObject;
  62986. };
  62987. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62988. var scene = this.getScene();
  62989. if (!scene) {
  62990. return;
  62991. }
  62992. var index = scene.multiMaterials.indexOf(this);
  62993. if (index >= 0) {
  62994. scene.multiMaterials.splice(index, 1);
  62995. }
  62996. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62997. };
  62998. return MultiMaterial;
  62999. }(BABYLON.Material));
  63000. BABYLON.MultiMaterial = MultiMaterial;
  63001. })(BABYLON || (BABYLON = {}));
  63002. //# sourceMappingURL=babylon.multiMaterial.js.map
  63003. var BABYLON;
  63004. (function (BABYLON) {
  63005. var FreeCameraTouchInput = /** @class */ (function () {
  63006. function FreeCameraTouchInput() {
  63007. this._offsetX = null;
  63008. this._offsetY = null;
  63009. this._pointerPressed = new Array();
  63010. this.touchAngularSensibility = 200000.0;
  63011. this.touchMoveSensibility = 250.0;
  63012. }
  63013. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63014. var _this = this;
  63015. var previousPosition = null;
  63016. if (this._pointerInput === undefined) {
  63017. this._onLostFocus = function (evt) {
  63018. _this._offsetX = null;
  63019. _this._offsetY = null;
  63020. };
  63021. this._pointerInput = function (p, s) {
  63022. var evt = p.event;
  63023. if (evt.pointerType === "mouse") {
  63024. return;
  63025. }
  63026. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63027. if (!noPreventDefault) {
  63028. evt.preventDefault();
  63029. }
  63030. _this._pointerPressed.push(evt.pointerId);
  63031. if (_this._pointerPressed.length !== 1) {
  63032. return;
  63033. }
  63034. previousPosition = {
  63035. x: evt.clientX,
  63036. y: evt.clientY
  63037. };
  63038. }
  63039. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63040. if (!noPreventDefault) {
  63041. evt.preventDefault();
  63042. }
  63043. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63044. if (index === -1) {
  63045. return;
  63046. }
  63047. _this._pointerPressed.splice(index, 1);
  63048. if (index != 0) {
  63049. return;
  63050. }
  63051. previousPosition = null;
  63052. _this._offsetX = null;
  63053. _this._offsetY = null;
  63054. }
  63055. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63056. if (!noPreventDefault) {
  63057. evt.preventDefault();
  63058. }
  63059. if (!previousPosition) {
  63060. return;
  63061. }
  63062. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63063. if (index != 0) {
  63064. return;
  63065. }
  63066. _this._offsetX = evt.clientX - previousPosition.x;
  63067. _this._offsetY = -(evt.clientY - previousPosition.y);
  63068. }
  63069. };
  63070. }
  63071. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63072. if (this._onLostFocus) {
  63073. element.addEventListener("blur", this._onLostFocus);
  63074. }
  63075. };
  63076. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63077. if (this._pointerInput && element) {
  63078. if (this._observer) {
  63079. this.camera.getScene().onPointerObservable.remove(this._observer);
  63080. this._observer = null;
  63081. }
  63082. if (this._onLostFocus) {
  63083. element.removeEventListener("blur", this._onLostFocus);
  63084. this._onLostFocus = null;
  63085. }
  63086. this._pointerPressed = [];
  63087. this._offsetX = null;
  63088. this._offsetY = null;
  63089. }
  63090. };
  63091. FreeCameraTouchInput.prototype.checkInputs = function () {
  63092. if (this._offsetX && this._offsetY) {
  63093. var camera = this.camera;
  63094. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63095. if (this._pointerPressed.length > 1) {
  63096. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63097. }
  63098. else {
  63099. var speed = camera._computeLocalCameraSpeed();
  63100. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63101. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63102. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63103. }
  63104. }
  63105. };
  63106. FreeCameraTouchInput.prototype.getClassName = function () {
  63107. return "FreeCameraTouchInput";
  63108. };
  63109. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63110. return "touch";
  63111. };
  63112. __decorate([
  63113. BABYLON.serialize()
  63114. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63115. __decorate([
  63116. BABYLON.serialize()
  63117. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63118. return FreeCameraTouchInput;
  63119. }());
  63120. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63121. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63122. })(BABYLON || (BABYLON = {}));
  63123. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63124. var BABYLON;
  63125. (function (BABYLON) {
  63126. // We're mainly based on the logic defined into the FreeCamera code
  63127. var TouchCamera = /** @class */ (function (_super) {
  63128. __extends(TouchCamera, _super);
  63129. //-- end properties for backward compatibility for inputs
  63130. function TouchCamera(name, position, scene) {
  63131. var _this = _super.call(this, name, position, scene) || this;
  63132. _this.inputs.addTouch();
  63133. _this._setupInputs();
  63134. return _this;
  63135. }
  63136. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63137. //-- Begin properties for backward compatibility for inputs
  63138. get: function () {
  63139. var touch = this.inputs.attached["touch"];
  63140. if (touch)
  63141. return touch.touchAngularSensibility;
  63142. return 0;
  63143. },
  63144. set: function (value) {
  63145. var touch = this.inputs.attached["touch"];
  63146. if (touch)
  63147. touch.touchAngularSensibility = value;
  63148. },
  63149. enumerable: true,
  63150. configurable: true
  63151. });
  63152. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63153. get: function () {
  63154. var touch = this.inputs.attached["touch"];
  63155. if (touch)
  63156. return touch.touchMoveSensibility;
  63157. return 0;
  63158. },
  63159. set: function (value) {
  63160. var touch = this.inputs.attached["touch"];
  63161. if (touch)
  63162. touch.touchMoveSensibility = value;
  63163. },
  63164. enumerable: true,
  63165. configurable: true
  63166. });
  63167. TouchCamera.prototype.getClassName = function () {
  63168. return "TouchCamera";
  63169. };
  63170. TouchCamera.prototype._setupInputs = function () {
  63171. var mouse = this.inputs.attached["mouse"];
  63172. if (mouse) {
  63173. mouse.touchEnabled = false;
  63174. }
  63175. };
  63176. return TouchCamera;
  63177. }(BABYLON.FreeCamera));
  63178. BABYLON.TouchCamera = TouchCamera;
  63179. })(BABYLON || (BABYLON = {}));
  63180. //# sourceMappingURL=babylon.touchCamera.js.map
  63181. var BABYLON;
  63182. (function (BABYLON) {
  63183. var ProceduralTexture = /** @class */ (function (_super) {
  63184. __extends(ProceduralTexture, _super);
  63185. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63186. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63187. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63188. if (isCube === void 0) { isCube = false; }
  63189. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63190. _this.isCube = isCube;
  63191. _this.isEnabled = true;
  63192. _this._currentRefreshId = -1;
  63193. _this._refreshRate = 1;
  63194. _this._vertexBuffers = {};
  63195. _this._uniforms = new Array();
  63196. _this._samplers = new Array();
  63197. _this._textures = {};
  63198. _this._floats = {};
  63199. _this._floatsArrays = {};
  63200. _this._colors3 = {};
  63201. _this._colors4 = {};
  63202. _this._vectors2 = {};
  63203. _this._vectors3 = {};
  63204. _this._matrices = {};
  63205. _this._fallbackTextureUsed = false;
  63206. scene._proceduralTextures.push(_this);
  63207. _this._engine = scene.getEngine();
  63208. _this.name = name;
  63209. _this.isRenderTarget = true;
  63210. _this._size = size;
  63211. _this._generateMipMaps = generateMipMaps;
  63212. _this.setFragment(fragment);
  63213. _this._fallbackTexture = fallbackTexture;
  63214. if (isCube) {
  63215. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63216. _this.setFloat("face", 0);
  63217. }
  63218. else {
  63219. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63220. }
  63221. // VBO
  63222. var vertices = [];
  63223. vertices.push(1, 1);
  63224. vertices.push(-1, 1);
  63225. vertices.push(-1, -1);
  63226. vertices.push(1, -1);
  63227. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63228. _this._createIndexBuffer();
  63229. return _this;
  63230. }
  63231. ProceduralTexture.prototype._createIndexBuffer = function () {
  63232. var engine = this._engine;
  63233. // Indices
  63234. var indices = [];
  63235. indices.push(0);
  63236. indices.push(1);
  63237. indices.push(2);
  63238. indices.push(0);
  63239. indices.push(2);
  63240. indices.push(3);
  63241. this._indexBuffer = engine.createIndexBuffer(indices);
  63242. };
  63243. ProceduralTexture.prototype._rebuild = function () {
  63244. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63245. if (vb) {
  63246. vb._rebuild();
  63247. }
  63248. this._createIndexBuffer();
  63249. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63250. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63251. }
  63252. };
  63253. ProceduralTexture.prototype.reset = function () {
  63254. if (this._effect === undefined) {
  63255. return;
  63256. }
  63257. var engine = this._engine;
  63258. engine._releaseEffect(this._effect);
  63259. };
  63260. ProceduralTexture.prototype.isReady = function () {
  63261. var _this = this;
  63262. var engine = this._engine;
  63263. var shaders;
  63264. if (!this._fragment) {
  63265. return false;
  63266. }
  63267. if (this._fallbackTextureUsed) {
  63268. return true;
  63269. }
  63270. if (this._fragment.fragmentElement !== undefined) {
  63271. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63272. }
  63273. else {
  63274. shaders = { vertex: "procedural", fragment: this._fragment };
  63275. }
  63276. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63277. _this.releaseInternalTexture();
  63278. if (_this._fallbackTexture) {
  63279. _this._texture = _this._fallbackTexture._texture;
  63280. if (_this._texture) {
  63281. _this._texture.incrementReferences();
  63282. }
  63283. }
  63284. _this._fallbackTextureUsed = true;
  63285. });
  63286. return this._effect.isReady();
  63287. };
  63288. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63289. this._currentRefreshId = -1;
  63290. };
  63291. ProceduralTexture.prototype.setFragment = function (fragment) {
  63292. this._fragment = fragment;
  63293. };
  63294. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63295. get: function () {
  63296. return this._refreshRate;
  63297. },
  63298. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63299. set: function (value) {
  63300. this._refreshRate = value;
  63301. this.resetRefreshCounter();
  63302. },
  63303. enumerable: true,
  63304. configurable: true
  63305. });
  63306. ProceduralTexture.prototype._shouldRender = function () {
  63307. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63308. return false;
  63309. }
  63310. if (this._fallbackTextureUsed) {
  63311. return false;
  63312. }
  63313. if (this._currentRefreshId === -1) {
  63314. this._currentRefreshId = 1;
  63315. return true;
  63316. }
  63317. if (this.refreshRate === this._currentRefreshId) {
  63318. this._currentRefreshId = 1;
  63319. return true;
  63320. }
  63321. this._currentRefreshId++;
  63322. return false;
  63323. };
  63324. ProceduralTexture.prototype.getRenderSize = function () {
  63325. return this._size;
  63326. };
  63327. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63328. if (this._fallbackTextureUsed) {
  63329. return;
  63330. }
  63331. this.releaseInternalTexture();
  63332. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63333. };
  63334. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63335. if (this._uniforms.indexOf(uniformName) === -1) {
  63336. this._uniforms.push(uniformName);
  63337. }
  63338. };
  63339. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63340. if (this._samplers.indexOf(name) === -1) {
  63341. this._samplers.push(name);
  63342. }
  63343. this._textures[name] = texture;
  63344. return this;
  63345. };
  63346. ProceduralTexture.prototype.setFloat = function (name, value) {
  63347. this._checkUniform(name);
  63348. this._floats[name] = value;
  63349. return this;
  63350. };
  63351. ProceduralTexture.prototype.setFloats = function (name, value) {
  63352. this._checkUniform(name);
  63353. this._floatsArrays[name] = value;
  63354. return this;
  63355. };
  63356. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63357. this._checkUniform(name);
  63358. this._colors3[name] = value;
  63359. return this;
  63360. };
  63361. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63362. this._checkUniform(name);
  63363. this._colors4[name] = value;
  63364. return this;
  63365. };
  63366. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63367. this._checkUniform(name);
  63368. this._vectors2[name] = value;
  63369. return this;
  63370. };
  63371. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63372. this._checkUniform(name);
  63373. this._vectors3[name] = value;
  63374. return this;
  63375. };
  63376. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63377. this._checkUniform(name);
  63378. this._matrices[name] = value;
  63379. return this;
  63380. };
  63381. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63382. var scene = this.getScene();
  63383. if (!scene) {
  63384. return;
  63385. }
  63386. var engine = this._engine;
  63387. // Render
  63388. engine.enableEffect(this._effect);
  63389. engine.setState(false);
  63390. // Texture
  63391. for (var name in this._textures) {
  63392. this._effect.setTexture(name, this._textures[name]);
  63393. }
  63394. // Float
  63395. for (name in this._floats) {
  63396. this._effect.setFloat(name, this._floats[name]);
  63397. }
  63398. // Floats
  63399. for (name in this._floatsArrays) {
  63400. this._effect.setArray(name, this._floatsArrays[name]);
  63401. }
  63402. // Color3
  63403. for (name in this._colors3) {
  63404. this._effect.setColor3(name, this._colors3[name]);
  63405. }
  63406. // Color4
  63407. for (name in this._colors4) {
  63408. var color = this._colors4[name];
  63409. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63410. }
  63411. // Vector2
  63412. for (name in this._vectors2) {
  63413. this._effect.setVector2(name, this._vectors2[name]);
  63414. }
  63415. // Vector3
  63416. for (name in this._vectors3) {
  63417. this._effect.setVector3(name, this._vectors3[name]);
  63418. }
  63419. // Matrix
  63420. for (name in this._matrices) {
  63421. this._effect.setMatrix(name, this._matrices[name]);
  63422. }
  63423. if (!this._texture) {
  63424. return;
  63425. }
  63426. if (this.isCube) {
  63427. for (var face = 0; face < 6; face++) {
  63428. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63429. // VBOs
  63430. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63431. this._effect.setFloat("face", face);
  63432. // Clear
  63433. engine.clear(scene.clearColor, true, true, true);
  63434. // Draw order
  63435. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63436. // Mipmaps
  63437. if (face === 5) {
  63438. engine.generateMipMapsForCubemap(this._texture);
  63439. }
  63440. }
  63441. }
  63442. else {
  63443. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63444. // VBOs
  63445. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63446. // Clear
  63447. engine.clear(scene.clearColor, true, true, true);
  63448. // Draw order
  63449. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63450. }
  63451. // Unbind
  63452. engine.unBindFramebuffer(this._texture, this.isCube);
  63453. if (this.onGenerated) {
  63454. this.onGenerated();
  63455. }
  63456. };
  63457. ProceduralTexture.prototype.clone = function () {
  63458. var textureSize = this.getSize();
  63459. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63460. // Base texture
  63461. newTexture.hasAlpha = this.hasAlpha;
  63462. newTexture.level = this.level;
  63463. // RenderTarget Texture
  63464. newTexture.coordinatesMode = this.coordinatesMode;
  63465. return newTexture;
  63466. };
  63467. ProceduralTexture.prototype.dispose = function () {
  63468. var scene = this.getScene();
  63469. if (!scene) {
  63470. return;
  63471. }
  63472. var index = scene._proceduralTextures.indexOf(this);
  63473. if (index >= 0) {
  63474. scene._proceduralTextures.splice(index, 1);
  63475. }
  63476. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63477. if (vertexBuffer) {
  63478. vertexBuffer.dispose();
  63479. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63480. }
  63481. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63482. this._indexBuffer = null;
  63483. }
  63484. _super.prototype.dispose.call(this);
  63485. };
  63486. return ProceduralTexture;
  63487. }(BABYLON.Texture));
  63488. BABYLON.ProceduralTexture = ProceduralTexture;
  63489. })(BABYLON || (BABYLON = {}));
  63490. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63491. var BABYLON;
  63492. (function (BABYLON) {
  63493. var CustomProceduralTexture = /** @class */ (function (_super) {
  63494. __extends(CustomProceduralTexture, _super);
  63495. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63496. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63497. _this._animate = true;
  63498. _this._time = 0;
  63499. _this._texturePath = texturePath;
  63500. //Try to load json
  63501. _this.loadJson(texturePath);
  63502. _this.refreshRate = 1;
  63503. return _this;
  63504. }
  63505. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63506. var _this = this;
  63507. var noConfigFile = function () {
  63508. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63509. try {
  63510. _this.setFragment(_this._texturePath);
  63511. }
  63512. catch (ex) {
  63513. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63514. }
  63515. };
  63516. var configFileUrl = jsonUrl + "/config.json";
  63517. var xhr = new XMLHttpRequest();
  63518. xhr.open("GET", configFileUrl, true);
  63519. xhr.addEventListener("load", function () {
  63520. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63521. try {
  63522. _this._config = JSON.parse(xhr.response);
  63523. _this.updateShaderUniforms();
  63524. _this.updateTextures();
  63525. _this.setFragment(_this._texturePath + "/custom");
  63526. _this._animate = _this._config.animate;
  63527. _this.refreshRate = _this._config.refreshrate;
  63528. }
  63529. catch (ex) {
  63530. noConfigFile();
  63531. }
  63532. }
  63533. else {
  63534. noConfigFile();
  63535. }
  63536. }, false);
  63537. xhr.addEventListener("error", function () {
  63538. noConfigFile();
  63539. }, false);
  63540. try {
  63541. xhr.send();
  63542. }
  63543. catch (ex) {
  63544. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63545. }
  63546. };
  63547. CustomProceduralTexture.prototype.isReady = function () {
  63548. if (!_super.prototype.isReady.call(this)) {
  63549. return false;
  63550. }
  63551. for (var name in this._textures) {
  63552. var texture = this._textures[name];
  63553. if (!texture.isReady()) {
  63554. return false;
  63555. }
  63556. }
  63557. return true;
  63558. };
  63559. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63560. var scene = this.getScene();
  63561. if (this._animate && scene) {
  63562. this._time += scene.getAnimationRatio() * 0.03;
  63563. this.updateShaderUniforms();
  63564. }
  63565. _super.prototype.render.call(this, useCameraPostProcess);
  63566. };
  63567. CustomProceduralTexture.prototype.updateTextures = function () {
  63568. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63569. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63570. }
  63571. };
  63572. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63573. if (this._config) {
  63574. for (var j = 0; j < this._config.uniforms.length; j++) {
  63575. var uniform = this._config.uniforms[j];
  63576. switch (uniform.type) {
  63577. case "float":
  63578. this.setFloat(uniform.name, uniform.value);
  63579. break;
  63580. case "color3":
  63581. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63582. break;
  63583. case "color4":
  63584. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63585. break;
  63586. case "vector2":
  63587. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63588. break;
  63589. case "vector3":
  63590. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63591. break;
  63592. }
  63593. }
  63594. }
  63595. this.setFloat("time", this._time);
  63596. };
  63597. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63598. get: function () {
  63599. return this._animate;
  63600. },
  63601. set: function (value) {
  63602. this._animate = value;
  63603. },
  63604. enumerable: true,
  63605. configurable: true
  63606. });
  63607. return CustomProceduralTexture;
  63608. }(BABYLON.ProceduralTexture));
  63609. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63610. })(BABYLON || (BABYLON = {}));
  63611. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63612. var BABYLON;
  63613. (function (BABYLON) {
  63614. var FreeCameraGamepadInput = /** @class */ (function () {
  63615. function FreeCameraGamepadInput() {
  63616. this.gamepadAngularSensibility = 200;
  63617. this.gamepadMoveSensibility = 40;
  63618. // private members
  63619. this._cameraTransform = BABYLON.Matrix.Identity();
  63620. this._deltaTransform = BABYLON.Vector3.Zero();
  63621. this._vector3 = BABYLON.Vector3.Zero();
  63622. this._vector2 = BABYLON.Vector2.Zero();
  63623. }
  63624. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63625. var _this = this;
  63626. var manager = this.camera.getScene().gamepadManager;
  63627. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63628. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63629. // prioritize XBOX gamepads.
  63630. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63631. _this.gamepad = gamepad;
  63632. }
  63633. }
  63634. });
  63635. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63636. if (_this.gamepad === gamepad) {
  63637. _this.gamepad = null;
  63638. }
  63639. });
  63640. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63641. };
  63642. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63643. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63644. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63645. this.gamepad = null;
  63646. };
  63647. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63648. if (this.gamepad && this.gamepad.leftStick) {
  63649. var camera = this.camera;
  63650. var LSValues = this.gamepad.leftStick;
  63651. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63652. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63653. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63654. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63655. var RSValues = this.gamepad.rightStick;
  63656. if (RSValues) {
  63657. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63658. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63659. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63660. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63661. }
  63662. else {
  63663. RSValues = { x: 0, y: 0 };
  63664. }
  63665. if (!camera.rotationQuaternion) {
  63666. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63667. }
  63668. else {
  63669. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63670. }
  63671. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63672. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63673. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63674. camera.cameraDirection.addInPlace(this._deltaTransform);
  63675. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63676. camera.cameraRotation.addInPlace(this._vector2);
  63677. }
  63678. };
  63679. FreeCameraGamepadInput.prototype.getClassName = function () {
  63680. return "FreeCameraGamepadInput";
  63681. };
  63682. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63683. return "gamepad";
  63684. };
  63685. __decorate([
  63686. BABYLON.serialize()
  63687. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63688. __decorate([
  63689. BABYLON.serialize()
  63690. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63691. return FreeCameraGamepadInput;
  63692. }());
  63693. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63694. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63695. })(BABYLON || (BABYLON = {}));
  63696. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63697. var BABYLON;
  63698. (function (BABYLON) {
  63699. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63700. function ArcRotateCameraGamepadInput() {
  63701. this.gamepadRotationSensibility = 80;
  63702. this.gamepadMoveSensibility = 40;
  63703. }
  63704. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63705. var _this = this;
  63706. var manager = this.camera.getScene().gamepadManager;
  63707. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63708. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63709. // prioritize XBOX gamepads.
  63710. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63711. _this.gamepad = gamepad;
  63712. }
  63713. }
  63714. });
  63715. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63716. if (_this.gamepad === gamepad) {
  63717. _this.gamepad = null;
  63718. }
  63719. });
  63720. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63721. };
  63722. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63723. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63724. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63725. this.gamepad = null;
  63726. };
  63727. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63728. if (this.gamepad) {
  63729. var camera = this.camera;
  63730. var RSValues = this.gamepad.rightStick;
  63731. if (RSValues) {
  63732. if (RSValues.x != 0) {
  63733. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63734. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63735. camera.inertialAlphaOffset += normalizedRX;
  63736. }
  63737. }
  63738. if (RSValues.y != 0) {
  63739. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63740. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63741. camera.inertialBetaOffset += normalizedRY;
  63742. }
  63743. }
  63744. }
  63745. var LSValues = this.gamepad.leftStick;
  63746. if (LSValues && LSValues.y != 0) {
  63747. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63748. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63749. this.camera.inertialRadiusOffset -= normalizedLY;
  63750. }
  63751. }
  63752. }
  63753. };
  63754. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63755. return "ArcRotateCameraGamepadInput";
  63756. };
  63757. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63758. return "gamepad";
  63759. };
  63760. __decorate([
  63761. BABYLON.serialize()
  63762. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63763. __decorate([
  63764. BABYLON.serialize()
  63765. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63766. return ArcRotateCameraGamepadInput;
  63767. }());
  63768. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63769. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63770. })(BABYLON || (BABYLON = {}));
  63771. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63772. var BABYLON;
  63773. (function (BABYLON) {
  63774. var GamepadManager = /** @class */ (function () {
  63775. function GamepadManager(_scene) {
  63776. var _this = this;
  63777. this._scene = _scene;
  63778. this._babylonGamepads = [];
  63779. this._oneGamepadConnected = false;
  63780. this._isMonitoring = false;
  63781. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63782. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63783. this._gamepadEventSupported = false;
  63784. }
  63785. else {
  63786. this._gamepadEventSupported = 'GamepadEvent' in window;
  63787. this._gamepadSupport = (navigator.getGamepads ||
  63788. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63789. }
  63790. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63791. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63792. for (var i in _this._babylonGamepads) {
  63793. var gamepad = _this._babylonGamepads[i];
  63794. if (gamepad && gamepad._isConnected) {
  63795. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63796. }
  63797. }
  63798. });
  63799. this._onGamepadConnectedEvent = function (evt) {
  63800. var gamepad = evt.gamepad;
  63801. if (gamepad.index in _this._babylonGamepads) {
  63802. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63803. return;
  63804. }
  63805. }
  63806. var newGamepad;
  63807. if (_this._babylonGamepads[gamepad.index]) {
  63808. newGamepad = _this._babylonGamepads[gamepad.index];
  63809. newGamepad.browserGamepad = gamepad;
  63810. newGamepad._isConnected = true;
  63811. }
  63812. else {
  63813. newGamepad = _this._addNewGamepad(gamepad);
  63814. }
  63815. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63816. _this._startMonitoringGamepads();
  63817. };
  63818. this._onGamepadDisconnectedEvent = function (evt) {
  63819. var gamepad = evt.gamepad;
  63820. // Remove the gamepad from the list of gamepads to monitor.
  63821. for (var i in _this._babylonGamepads) {
  63822. if (_this._babylonGamepads[i].index === gamepad.index) {
  63823. var disconnectedGamepad = _this._babylonGamepads[i];
  63824. disconnectedGamepad._isConnected = false;
  63825. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63826. break;
  63827. }
  63828. }
  63829. };
  63830. if (this._gamepadSupport) {
  63831. //first add already-connected gamepads
  63832. this._updateGamepadObjects();
  63833. if (this._babylonGamepads.length) {
  63834. this._startMonitoringGamepads();
  63835. }
  63836. // Checking if the gamepad connected event is supported (like in Firefox)
  63837. if (this._gamepadEventSupported) {
  63838. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63839. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63840. }
  63841. else {
  63842. this._startMonitoringGamepads();
  63843. }
  63844. }
  63845. }
  63846. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63847. get: function () {
  63848. return this._babylonGamepads;
  63849. },
  63850. enumerable: true,
  63851. configurable: true
  63852. });
  63853. GamepadManager.prototype.getGamepadByType = function (type) {
  63854. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63855. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63856. var gamepad = _a[_i];
  63857. if (gamepad && gamepad.type === type) {
  63858. return gamepad;
  63859. }
  63860. }
  63861. return null;
  63862. };
  63863. GamepadManager.prototype.dispose = function () {
  63864. if (this._gamepadEventSupported) {
  63865. if (this._onGamepadConnectedEvent) {
  63866. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63867. }
  63868. if (this._onGamepadDisconnectedEvent) {
  63869. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63870. }
  63871. this._onGamepadConnectedEvent = null;
  63872. this._onGamepadDisconnectedEvent = null;
  63873. }
  63874. this._babylonGamepads.forEach(function (gamepad) {
  63875. gamepad.dispose();
  63876. });
  63877. this.onGamepadConnectedObservable.clear();
  63878. this.onGamepadDisconnectedObservable.clear();
  63879. this._oneGamepadConnected = false;
  63880. this._stopMonitoringGamepads();
  63881. this._babylonGamepads = [];
  63882. };
  63883. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63884. if (!this._oneGamepadConnected) {
  63885. this._oneGamepadConnected = true;
  63886. }
  63887. var newGamepad;
  63888. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63889. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63890. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63891. }
  63892. else if (gamepad.pose) {
  63893. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63894. }
  63895. else {
  63896. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63897. }
  63898. this._babylonGamepads[newGamepad.index] = newGamepad;
  63899. return newGamepad;
  63900. };
  63901. GamepadManager.prototype._startMonitoringGamepads = function () {
  63902. if (!this._isMonitoring) {
  63903. this._isMonitoring = true;
  63904. //back-comp
  63905. if (!this._scene) {
  63906. this._checkGamepadsStatus();
  63907. }
  63908. }
  63909. };
  63910. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63911. this._isMonitoring = false;
  63912. };
  63913. GamepadManager.prototype._checkGamepadsStatus = function () {
  63914. var _this = this;
  63915. // Hack to be compatible Chrome
  63916. this._updateGamepadObjects();
  63917. for (var i in this._babylonGamepads) {
  63918. var gamepad = this._babylonGamepads[i];
  63919. if (!gamepad || !gamepad.isConnected) {
  63920. continue;
  63921. }
  63922. gamepad.update();
  63923. }
  63924. if (this._isMonitoring && !this._scene) {
  63925. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63926. }
  63927. };
  63928. // This function is called only on Chrome, which does not properly support
  63929. // connection/disconnection events and forces you to recopy again the gamepad object
  63930. GamepadManager.prototype._updateGamepadObjects = function () {
  63931. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63932. for (var i = 0; i < gamepads.length; i++) {
  63933. if (gamepads[i]) {
  63934. if (!this._babylonGamepads[gamepads[i].index]) {
  63935. var newGamepad = this._addNewGamepad(gamepads[i]);
  63936. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63937. }
  63938. else {
  63939. // Forced to copy again this object for Chrome for unknown reason
  63940. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63941. if (!this._babylonGamepads[i].isConnected) {
  63942. this._babylonGamepads[i]._isConnected = true;
  63943. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63944. }
  63945. }
  63946. }
  63947. }
  63948. };
  63949. return GamepadManager;
  63950. }());
  63951. BABYLON.GamepadManager = GamepadManager;
  63952. })(BABYLON || (BABYLON = {}));
  63953. //# sourceMappingURL=babylon.gamepadManager.js.map
  63954. var BABYLON;
  63955. (function (BABYLON) {
  63956. var StickValues = /** @class */ (function () {
  63957. function StickValues(x, y) {
  63958. this.x = x;
  63959. this.y = y;
  63960. }
  63961. return StickValues;
  63962. }());
  63963. BABYLON.StickValues = StickValues;
  63964. var Gamepad = /** @class */ (function () {
  63965. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63966. if (leftStickX === void 0) { leftStickX = 0; }
  63967. if (leftStickY === void 0) { leftStickY = 1; }
  63968. if (rightStickX === void 0) { rightStickX = 2; }
  63969. if (rightStickY === void 0) { rightStickY = 3; }
  63970. this.id = id;
  63971. this.index = index;
  63972. this.browserGamepad = browserGamepad;
  63973. this._isConnected = true;
  63974. this._invertLeftStickY = false;
  63975. this.type = Gamepad.GAMEPAD;
  63976. this._leftStickAxisX = leftStickX;
  63977. this._leftStickAxisY = leftStickY;
  63978. this._rightStickAxisX = rightStickX;
  63979. this._rightStickAxisY = rightStickY;
  63980. if (this.browserGamepad.axes.length >= 2) {
  63981. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63982. }
  63983. if (this.browserGamepad.axes.length >= 4) {
  63984. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63985. }
  63986. }
  63987. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63988. get: function () {
  63989. return this._isConnected;
  63990. },
  63991. enumerable: true,
  63992. configurable: true
  63993. });
  63994. Gamepad.prototype.onleftstickchanged = function (callback) {
  63995. this._onleftstickchanged = callback;
  63996. };
  63997. Gamepad.prototype.onrightstickchanged = function (callback) {
  63998. this._onrightstickchanged = callback;
  63999. };
  64000. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64001. get: function () {
  64002. return this._leftStick;
  64003. },
  64004. set: function (newValues) {
  64005. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64006. this._onleftstickchanged(newValues);
  64007. }
  64008. this._leftStick = newValues;
  64009. },
  64010. enumerable: true,
  64011. configurable: true
  64012. });
  64013. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64014. get: function () {
  64015. return this._rightStick;
  64016. },
  64017. set: function (newValues) {
  64018. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64019. this._onrightstickchanged(newValues);
  64020. }
  64021. this._rightStick = newValues;
  64022. },
  64023. enumerable: true,
  64024. configurable: true
  64025. });
  64026. Gamepad.prototype.update = function () {
  64027. if (this._leftStick) {
  64028. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64029. if (this._invertLeftStickY) {
  64030. this.leftStick.y *= -1;
  64031. }
  64032. }
  64033. if (this._rightStick) {
  64034. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64035. }
  64036. };
  64037. Gamepad.prototype.dispose = function () {
  64038. };
  64039. Gamepad.GAMEPAD = 0;
  64040. Gamepad.GENERIC = 1;
  64041. Gamepad.XBOX = 2;
  64042. Gamepad.POSE_ENABLED = 3;
  64043. return Gamepad;
  64044. }());
  64045. BABYLON.Gamepad = Gamepad;
  64046. var GenericPad = /** @class */ (function (_super) {
  64047. __extends(GenericPad, _super);
  64048. function GenericPad(id, index, browserGamepad) {
  64049. var _this = _super.call(this, id, index, browserGamepad) || this;
  64050. _this.onButtonDownObservable = new BABYLON.Observable();
  64051. _this.onButtonUpObservable = new BABYLON.Observable();
  64052. _this.type = Gamepad.GENERIC;
  64053. _this._buttons = new Array(browserGamepad.buttons.length);
  64054. return _this;
  64055. }
  64056. GenericPad.prototype.onbuttondown = function (callback) {
  64057. this._onbuttondown = callback;
  64058. };
  64059. GenericPad.prototype.onbuttonup = function (callback) {
  64060. this._onbuttonup = callback;
  64061. };
  64062. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64063. if (newValue !== currentValue) {
  64064. if (newValue === 1) {
  64065. if (this._onbuttondown) {
  64066. this._onbuttondown(buttonIndex);
  64067. }
  64068. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64069. }
  64070. if (newValue === 0) {
  64071. if (this._onbuttonup) {
  64072. this._onbuttonup(buttonIndex);
  64073. }
  64074. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64075. }
  64076. }
  64077. return newValue;
  64078. };
  64079. GenericPad.prototype.update = function () {
  64080. _super.prototype.update.call(this);
  64081. for (var index = 0; index < this._buttons.length; index++) {
  64082. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64083. }
  64084. };
  64085. GenericPad.prototype.dispose = function () {
  64086. _super.prototype.dispose.call(this);
  64087. this.onButtonDownObservable.clear();
  64088. this.onButtonUpObservable.clear();
  64089. };
  64090. return GenericPad;
  64091. }(Gamepad));
  64092. BABYLON.GenericPad = GenericPad;
  64093. })(BABYLON || (BABYLON = {}));
  64094. //# sourceMappingURL=babylon.gamepad.js.map
  64095. var BABYLON;
  64096. (function (BABYLON) {
  64097. var Xbox360Button;
  64098. (function (Xbox360Button) {
  64099. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64100. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64101. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64102. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64103. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64104. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64105. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64106. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64107. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64108. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64109. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64110. var Xbox360Dpad;
  64111. (function (Xbox360Dpad) {
  64112. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64113. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64114. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64115. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64116. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64117. var Xbox360Pad = /** @class */ (function (_super) {
  64118. __extends(Xbox360Pad, _super);
  64119. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64120. if (xboxOne === void 0) { xboxOne = false; }
  64121. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64122. _this._leftTrigger = 0;
  64123. _this._rightTrigger = 0;
  64124. _this.onButtonDownObservable = new BABYLON.Observable();
  64125. _this.onButtonUpObservable = new BABYLON.Observable();
  64126. _this.onPadDownObservable = new BABYLON.Observable();
  64127. _this.onPadUpObservable = new BABYLON.Observable();
  64128. _this._buttonA = 0;
  64129. _this._buttonB = 0;
  64130. _this._buttonX = 0;
  64131. _this._buttonY = 0;
  64132. _this._buttonBack = 0;
  64133. _this._buttonStart = 0;
  64134. _this._buttonLB = 0;
  64135. _this._buttonRB = 0;
  64136. _this._buttonLeftStick = 0;
  64137. _this._buttonRightStick = 0;
  64138. _this._dPadUp = 0;
  64139. _this._dPadDown = 0;
  64140. _this._dPadLeft = 0;
  64141. _this._dPadRight = 0;
  64142. _this._isXboxOnePad = false;
  64143. _this.type = BABYLON.Gamepad.XBOX;
  64144. _this._isXboxOnePad = xboxOne;
  64145. return _this;
  64146. }
  64147. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64148. this._onlefttriggerchanged = callback;
  64149. };
  64150. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64151. this._onrighttriggerchanged = callback;
  64152. };
  64153. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64154. get: function () {
  64155. return this._leftTrigger;
  64156. },
  64157. set: function (newValue) {
  64158. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64159. this._onlefttriggerchanged(newValue);
  64160. }
  64161. this._leftTrigger = newValue;
  64162. },
  64163. enumerable: true,
  64164. configurable: true
  64165. });
  64166. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64167. get: function () {
  64168. return this._rightTrigger;
  64169. },
  64170. set: function (newValue) {
  64171. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64172. this._onrighttriggerchanged(newValue);
  64173. }
  64174. this._rightTrigger = newValue;
  64175. },
  64176. enumerable: true,
  64177. configurable: true
  64178. });
  64179. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64180. this._onbuttondown = callback;
  64181. };
  64182. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64183. this._onbuttonup = callback;
  64184. };
  64185. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64186. this._ondpaddown = callback;
  64187. };
  64188. Xbox360Pad.prototype.ondpadup = function (callback) {
  64189. this._ondpadup = callback;
  64190. };
  64191. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64192. if (newValue !== currentValue) {
  64193. if (newValue === 1) {
  64194. if (this._onbuttondown) {
  64195. this._onbuttondown(buttonType);
  64196. }
  64197. this.onButtonDownObservable.notifyObservers(buttonType);
  64198. }
  64199. if (newValue === 0) {
  64200. if (this._onbuttonup) {
  64201. this._onbuttonup(buttonType);
  64202. }
  64203. this.onButtonUpObservable.notifyObservers(buttonType);
  64204. }
  64205. }
  64206. return newValue;
  64207. };
  64208. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64209. if (newValue !== currentValue) {
  64210. if (newValue === 1) {
  64211. if (this._ondpaddown) {
  64212. this._ondpaddown(buttonType);
  64213. }
  64214. this.onPadDownObservable.notifyObservers(buttonType);
  64215. }
  64216. if (newValue === 0) {
  64217. if (this._ondpadup) {
  64218. this._ondpadup(buttonType);
  64219. }
  64220. this.onPadUpObservable.notifyObservers(buttonType);
  64221. }
  64222. }
  64223. return newValue;
  64224. };
  64225. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64226. get: function () {
  64227. return this._buttonA;
  64228. },
  64229. set: function (value) {
  64230. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64231. },
  64232. enumerable: true,
  64233. configurable: true
  64234. });
  64235. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64236. get: function () {
  64237. return this._buttonB;
  64238. },
  64239. set: function (value) {
  64240. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64241. },
  64242. enumerable: true,
  64243. configurable: true
  64244. });
  64245. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64246. get: function () {
  64247. return this._buttonX;
  64248. },
  64249. set: function (value) {
  64250. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64251. },
  64252. enumerable: true,
  64253. configurable: true
  64254. });
  64255. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64256. get: function () {
  64257. return this._buttonY;
  64258. },
  64259. set: function (value) {
  64260. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64261. },
  64262. enumerable: true,
  64263. configurable: true
  64264. });
  64265. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64266. get: function () {
  64267. return this._buttonStart;
  64268. },
  64269. set: function (value) {
  64270. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64271. },
  64272. enumerable: true,
  64273. configurable: true
  64274. });
  64275. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64276. get: function () {
  64277. return this._buttonBack;
  64278. },
  64279. set: function (value) {
  64280. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64281. },
  64282. enumerable: true,
  64283. configurable: true
  64284. });
  64285. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64286. get: function () {
  64287. return this._buttonLB;
  64288. },
  64289. set: function (value) {
  64290. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64291. },
  64292. enumerable: true,
  64293. configurable: true
  64294. });
  64295. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64296. get: function () {
  64297. return this._buttonRB;
  64298. },
  64299. set: function (value) {
  64300. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64301. },
  64302. enumerable: true,
  64303. configurable: true
  64304. });
  64305. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64306. get: function () {
  64307. return this._buttonLeftStick;
  64308. },
  64309. set: function (value) {
  64310. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64311. },
  64312. enumerable: true,
  64313. configurable: true
  64314. });
  64315. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64316. get: function () {
  64317. return this._buttonRightStick;
  64318. },
  64319. set: function (value) {
  64320. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64321. },
  64322. enumerable: true,
  64323. configurable: true
  64324. });
  64325. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64326. get: function () {
  64327. return this._dPadUp;
  64328. },
  64329. set: function (value) {
  64330. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64331. },
  64332. enumerable: true,
  64333. configurable: true
  64334. });
  64335. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64336. get: function () {
  64337. return this._dPadDown;
  64338. },
  64339. set: function (value) {
  64340. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64341. },
  64342. enumerable: true,
  64343. configurable: true
  64344. });
  64345. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64346. get: function () {
  64347. return this._dPadLeft;
  64348. },
  64349. set: function (value) {
  64350. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64351. },
  64352. enumerable: true,
  64353. configurable: true
  64354. });
  64355. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64356. get: function () {
  64357. return this._dPadRight;
  64358. },
  64359. set: function (value) {
  64360. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64361. },
  64362. enumerable: true,
  64363. configurable: true
  64364. });
  64365. Xbox360Pad.prototype.update = function () {
  64366. _super.prototype.update.call(this);
  64367. if (this._isXboxOnePad) {
  64368. this.buttonA = this.browserGamepad.buttons[0].value;
  64369. this.buttonB = this.browserGamepad.buttons[1].value;
  64370. this.buttonX = this.browserGamepad.buttons[2].value;
  64371. this.buttonY = this.browserGamepad.buttons[3].value;
  64372. this.buttonLB = this.browserGamepad.buttons[4].value;
  64373. this.buttonRB = this.browserGamepad.buttons[5].value;
  64374. this.leftTrigger = this.browserGamepad.axes[2];
  64375. this.rightTrigger = this.browserGamepad.axes[5];
  64376. this.buttonBack = this.browserGamepad.buttons[9].value;
  64377. this.buttonStart = this.browserGamepad.buttons[8].value;
  64378. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64379. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64380. this.dPadUp = this.browserGamepad.buttons[11].value;
  64381. this.dPadDown = this.browserGamepad.buttons[12].value;
  64382. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64383. this.dPadRight = this.browserGamepad.buttons[14].value;
  64384. }
  64385. else {
  64386. this.buttonA = this.browserGamepad.buttons[0].value;
  64387. this.buttonB = this.browserGamepad.buttons[1].value;
  64388. this.buttonX = this.browserGamepad.buttons[2].value;
  64389. this.buttonY = this.browserGamepad.buttons[3].value;
  64390. this.buttonLB = this.browserGamepad.buttons[4].value;
  64391. this.buttonRB = this.browserGamepad.buttons[5].value;
  64392. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64393. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64394. this.buttonBack = this.browserGamepad.buttons[8].value;
  64395. this.buttonStart = this.browserGamepad.buttons[9].value;
  64396. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64397. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64398. this.dPadUp = this.browserGamepad.buttons[12].value;
  64399. this.dPadDown = this.browserGamepad.buttons[13].value;
  64400. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64401. this.dPadRight = this.browserGamepad.buttons[15].value;
  64402. }
  64403. };
  64404. Xbox360Pad.prototype.dispose = function () {
  64405. _super.prototype.dispose.call(this);
  64406. this.onButtonDownObservable.clear();
  64407. this.onButtonUpObservable.clear();
  64408. this.onPadDownObservable.clear();
  64409. this.onPadUpObservable.clear();
  64410. };
  64411. return Xbox360Pad;
  64412. }(BABYLON.Gamepad));
  64413. BABYLON.Xbox360Pad = Xbox360Pad;
  64414. })(BABYLON || (BABYLON = {}));
  64415. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64416. var BABYLON;
  64417. (function (BABYLON) {
  64418. var PoseEnabledControllerType;
  64419. (function (PoseEnabledControllerType) {
  64420. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64421. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64422. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64423. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64424. /**
  64425. * Google Daydream
  64426. */
  64427. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64428. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64429. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64430. var PoseEnabledControllerHelper = /** @class */ (function () {
  64431. function PoseEnabledControllerHelper() {
  64432. }
  64433. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64434. // Oculus Touch
  64435. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64436. return new BABYLON.OculusTouchController(vrGamepad);
  64437. }
  64438. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64439. return new BABYLON.WindowsMotionController(vrGamepad);
  64440. }
  64441. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64442. return new BABYLON.ViveController(vrGamepad);
  64443. }
  64444. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64445. return new BABYLON.GearVRController(vrGamepad);
  64446. }
  64447. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64448. return new BABYLON.DaydreamController(vrGamepad);
  64449. }
  64450. else {
  64451. return new BABYLON.GenericController(vrGamepad);
  64452. }
  64453. };
  64454. return PoseEnabledControllerHelper;
  64455. }());
  64456. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64457. var PoseEnabledController = /** @class */ (function (_super) {
  64458. __extends(PoseEnabledController, _super);
  64459. function PoseEnabledController(browserGamepad) {
  64460. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64461. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64462. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64463. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64464. // Represents device position and rotation in babylon space
  64465. _this.devicePosition = BABYLON.Vector3.Zero();
  64466. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64467. _this.deviceScaleFactor = 1;
  64468. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64469. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64470. /**
  64471. * Node to be used when casting a ray from the controller
  64472. */
  64473. _this._pointingPoseNode = null;
  64474. _this._workingMatrix = BABYLON.Matrix.Identity();
  64475. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64476. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64477. _this.position = BABYLON.Vector3.Zero();
  64478. _this.rotationQuaternion = new BABYLON.Quaternion();
  64479. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64480. _this._calculatedRotation = new BABYLON.Quaternion();
  64481. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64482. return _this;
  64483. }
  64484. PoseEnabledController.prototype.update = function () {
  64485. _super.prototype.update.call(this);
  64486. var pose = this.browserGamepad.pose;
  64487. this.updateFromDevice(pose);
  64488. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64489. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64490. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64491. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64492. if (this._mesh) {
  64493. this._mesh.position.copyFrom(this.devicePosition);
  64494. if (this._mesh.rotationQuaternion) {
  64495. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64496. }
  64497. }
  64498. };
  64499. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64500. if (poseData) {
  64501. this.rawPose = poseData;
  64502. if (poseData.position) {
  64503. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64504. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64505. this._deviceRoomPosition.z *= -1;
  64506. }
  64507. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64508. this._calculatedPosition.addInPlace(this.position);
  64509. }
  64510. var pose = this.rawPose;
  64511. if (poseData.orientation && pose.orientation) {
  64512. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64513. if (this._mesh) {
  64514. if (this._mesh.getScene().useRightHandedSystem) {
  64515. this._deviceRoomRotationQuaternion.z *= -1;
  64516. this._deviceRoomRotationQuaternion.w *= -1;
  64517. }
  64518. else {
  64519. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64520. }
  64521. }
  64522. // if the camera is set, rotate to the camera's rotation
  64523. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64524. }
  64525. }
  64526. };
  64527. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64528. if (this._mesh) {
  64529. this._mesh.parent = null;
  64530. }
  64531. this._mesh = mesh;
  64532. if (this._poseControlledCamera) {
  64533. this._mesh.parent = this._poseControlledCamera;
  64534. }
  64535. if (!this._mesh.rotationQuaternion) {
  64536. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64537. }
  64538. };
  64539. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64540. this._poseControlledCamera = camera;
  64541. if (this._mesh) {
  64542. this._mesh.parent = this._poseControlledCamera;
  64543. }
  64544. };
  64545. PoseEnabledController.prototype.dispose = function () {
  64546. if (this._mesh) {
  64547. this._mesh.dispose();
  64548. }
  64549. this._mesh = null;
  64550. _super.prototype.dispose.call(this);
  64551. };
  64552. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64553. get: function () {
  64554. return this._mesh;
  64555. },
  64556. enumerable: true,
  64557. configurable: true
  64558. });
  64559. PoseEnabledController.prototype.getForwardRay = function (length) {
  64560. if (length === void 0) { length = 100; }
  64561. if (!this.mesh) {
  64562. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64563. }
  64564. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  64565. var origin = m.getTranslation();
  64566. var forward = new BABYLON.Vector3(0, 0, -1);
  64567. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64568. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64569. return new BABYLON.Ray(origin, direction, length);
  64570. };
  64571. /**
  64572. * Name of the child mesh that can be used to cast a ray from the controller
  64573. */
  64574. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  64575. return PoseEnabledController;
  64576. }(BABYLON.Gamepad));
  64577. BABYLON.PoseEnabledController = PoseEnabledController;
  64578. })(BABYLON || (BABYLON = {}));
  64579. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64580. var BABYLON;
  64581. (function (BABYLON) {
  64582. var WebVRController = /** @class */ (function (_super) {
  64583. __extends(WebVRController, _super);
  64584. function WebVRController(vrGamepad) {
  64585. var _this = _super.call(this, vrGamepad) || this;
  64586. // Observables
  64587. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64588. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64589. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64590. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64591. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64592. _this.pad = { x: 0, y: 0 };
  64593. // avoid GC, store state in a tmp object
  64594. _this._changes = {
  64595. pressChanged: false,
  64596. touchChanged: false,
  64597. valueChanged: false,
  64598. changed: false
  64599. };
  64600. _this._buttons = new Array(vrGamepad.buttons.length);
  64601. _this.hand = vrGamepad.hand;
  64602. return _this;
  64603. }
  64604. WebVRController.prototype.onButtonStateChange = function (callback) {
  64605. this._onButtonStateChange = callback;
  64606. };
  64607. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64608. get: function () {
  64609. return this._defaultModel;
  64610. },
  64611. enumerable: true,
  64612. configurable: true
  64613. });
  64614. WebVRController.prototype.update = function () {
  64615. _super.prototype.update.call(this);
  64616. for (var index = 0; index < this._buttons.length; index++) {
  64617. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64618. }
  64619. ;
  64620. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64621. this.pad.x = this.leftStick.x;
  64622. this.pad.y = this.leftStick.y;
  64623. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64624. }
  64625. };
  64626. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64627. if (!newState) {
  64628. newState = {
  64629. pressed: false,
  64630. touched: false,
  64631. value: 0
  64632. };
  64633. }
  64634. if (!currentState) {
  64635. this._buttons[buttonIndex] = {
  64636. pressed: newState.pressed,
  64637. touched: newState.touched,
  64638. value: newState.value
  64639. };
  64640. return;
  64641. }
  64642. this._checkChanges(newState, currentState);
  64643. if (this._changes.changed) {
  64644. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64645. this._handleButtonChange(buttonIndex, newState, this._changes);
  64646. }
  64647. this._buttons[buttonIndex].pressed = newState.pressed;
  64648. this._buttons[buttonIndex].touched = newState.touched;
  64649. // oculus triggers are never 0, thou not touched.
  64650. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64651. };
  64652. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64653. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64654. this._changes.touchChanged = newState.touched !== currentState.touched;
  64655. this._changes.valueChanged = newState.value !== currentState.value;
  64656. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64657. return this._changes;
  64658. };
  64659. WebVRController.prototype.dispose = function () {
  64660. _super.prototype.dispose.call(this);
  64661. this.onTriggerStateChangedObservable.clear();
  64662. this.onMainButtonStateChangedObservable.clear();
  64663. this.onSecondaryButtonStateChangedObservable.clear();
  64664. this.onPadStateChangedObservable.clear();
  64665. this.onPadValuesChangedObservable.clear();
  64666. };
  64667. return WebVRController;
  64668. }(BABYLON.PoseEnabledController));
  64669. BABYLON.WebVRController = WebVRController;
  64670. })(BABYLON || (BABYLON = {}));
  64671. //# sourceMappingURL=babylon.webVRController.js.map
  64672. var BABYLON;
  64673. (function (BABYLON) {
  64674. var OculusTouchController = /** @class */ (function (_super) {
  64675. __extends(OculusTouchController, _super);
  64676. function OculusTouchController(vrGamepad) {
  64677. var _this = _super.call(this, vrGamepad) || this;
  64678. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64679. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64680. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64681. return _this;
  64682. }
  64683. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64684. var _this = this;
  64685. var meshName;
  64686. // Hand
  64687. if (this.hand === 'left') {
  64688. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64689. }
  64690. else {
  64691. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64692. }
  64693. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64694. /*
  64695. Parent Mesh name: oculus_touch_left
  64696. - body
  64697. - trigger
  64698. - thumbstick
  64699. - grip
  64700. - button_y
  64701. - button_x
  64702. - button_enter
  64703. */
  64704. _this._defaultModel = newMeshes[1];
  64705. _this.attachToMesh(_this._defaultModel);
  64706. if (meshLoaded) {
  64707. meshLoaded(_this._defaultModel);
  64708. }
  64709. });
  64710. };
  64711. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64712. // helper getters for left and right hand.
  64713. get: function () {
  64714. if (this.hand === 'right') {
  64715. return this.onMainButtonStateChangedObservable;
  64716. }
  64717. else {
  64718. throw new Error('No A button on left hand');
  64719. }
  64720. },
  64721. enumerable: true,
  64722. configurable: true
  64723. });
  64724. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64725. get: function () {
  64726. if (this.hand === 'right') {
  64727. return this.onSecondaryButtonStateChangedObservable;
  64728. }
  64729. else {
  64730. throw new Error('No B button on left hand');
  64731. }
  64732. },
  64733. enumerable: true,
  64734. configurable: true
  64735. });
  64736. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64737. get: function () {
  64738. if (this.hand === 'left') {
  64739. return this.onMainButtonStateChangedObservable;
  64740. }
  64741. else {
  64742. throw new Error('No X button on right hand');
  64743. }
  64744. },
  64745. enumerable: true,
  64746. configurable: true
  64747. });
  64748. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64749. get: function () {
  64750. if (this.hand === 'left') {
  64751. return this.onSecondaryButtonStateChangedObservable;
  64752. }
  64753. else {
  64754. throw new Error('No Y button on right hand');
  64755. }
  64756. },
  64757. enumerable: true,
  64758. configurable: true
  64759. });
  64760. /*
  64761. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64762. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64763. 2) secondary trigger (same)
  64764. 3) A (right) X (left), touch, pressed = value
  64765. 4) B / Y
  64766. 5) thumb rest
  64767. */
  64768. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64769. var notifyObject = state; //{ state: state, changes: changes };
  64770. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64771. switch (buttonIdx) {
  64772. case 0:
  64773. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64774. return;
  64775. case 1:// index trigger
  64776. if (this._defaultModel) {
  64777. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64778. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64779. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64780. }
  64781. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64782. return;
  64783. case 2:// secondary trigger
  64784. if (this._defaultModel) {
  64785. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64786. }
  64787. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64788. return;
  64789. case 3:
  64790. if (this._defaultModel) {
  64791. if (notifyObject.pressed) {
  64792. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64793. }
  64794. else {
  64795. (this._defaultModel.getChildren()[1]).position.y = 0;
  64796. }
  64797. }
  64798. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64799. return;
  64800. case 4:
  64801. if (this._defaultModel) {
  64802. if (notifyObject.pressed) {
  64803. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64804. }
  64805. else {
  64806. (this._defaultModel.getChildren()[2]).position.y = 0;
  64807. }
  64808. }
  64809. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64810. return;
  64811. case 5:
  64812. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64813. return;
  64814. }
  64815. };
  64816. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64817. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64818. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64819. return OculusTouchController;
  64820. }(BABYLON.WebVRController));
  64821. BABYLON.OculusTouchController = OculusTouchController;
  64822. })(BABYLON || (BABYLON = {}));
  64823. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64824. var BABYLON;
  64825. (function (BABYLON) {
  64826. var ViveController = /** @class */ (function (_super) {
  64827. __extends(ViveController, _super);
  64828. function ViveController(vrGamepad) {
  64829. var _this = _super.call(this, vrGamepad) || this;
  64830. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64831. _this._invertLeftStickY = true;
  64832. return _this;
  64833. }
  64834. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64835. var _this = this;
  64836. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64837. /*
  64838. Parent Mesh name: ViveWand
  64839. - body
  64840. - r_gripper
  64841. - l_gripper
  64842. - menu_button
  64843. - system_button
  64844. - trackpad
  64845. - trigger
  64846. - LED
  64847. */
  64848. _this._defaultModel = newMeshes[1];
  64849. _this.attachToMesh(_this._defaultModel);
  64850. if (meshLoaded) {
  64851. meshLoaded(_this._defaultModel);
  64852. }
  64853. });
  64854. };
  64855. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64856. get: function () {
  64857. return this.onMainButtonStateChangedObservable;
  64858. },
  64859. enumerable: true,
  64860. configurable: true
  64861. });
  64862. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64863. get: function () {
  64864. return this.onMainButtonStateChangedObservable;
  64865. },
  64866. enumerable: true,
  64867. configurable: true
  64868. });
  64869. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64870. get: function () {
  64871. return this.onSecondaryButtonStateChangedObservable;
  64872. },
  64873. enumerable: true,
  64874. configurable: true
  64875. });
  64876. /**
  64877. * Vive mapping:
  64878. * 0: touchpad
  64879. * 1: trigger
  64880. * 2: left AND right buttons
  64881. * 3: menu button
  64882. */
  64883. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64884. var notifyObject = state; //{ state: state, changes: changes };
  64885. switch (buttonIdx) {
  64886. case 0:
  64887. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64888. return;
  64889. case 1:// index trigger
  64890. if (this._defaultModel) {
  64891. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64892. }
  64893. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64894. return;
  64895. case 2:// left AND right button
  64896. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64897. return;
  64898. case 3:
  64899. if (this._defaultModel) {
  64900. if (notifyObject.pressed) {
  64901. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64902. }
  64903. else {
  64904. (this._defaultModel.getChildren()[2]).position.y = 0;
  64905. }
  64906. }
  64907. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64908. return;
  64909. }
  64910. };
  64911. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64912. ViveController.MODEL_FILENAME = 'wand.babylon';
  64913. return ViveController;
  64914. }(BABYLON.WebVRController));
  64915. BABYLON.ViveController = ViveController;
  64916. })(BABYLON || (BABYLON = {}));
  64917. //# sourceMappingURL=babylon.viveController.js.map
  64918. var BABYLON;
  64919. (function (BABYLON) {
  64920. var GenericController = /** @class */ (function (_super) {
  64921. __extends(GenericController, _super);
  64922. function GenericController(vrGamepad) {
  64923. return _super.call(this, vrGamepad) || this;
  64924. }
  64925. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64926. var _this = this;
  64927. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64928. _this._defaultModel = newMeshes[1];
  64929. _this.attachToMesh(_this._defaultModel);
  64930. if (meshLoaded) {
  64931. meshLoaded(_this._defaultModel);
  64932. }
  64933. });
  64934. };
  64935. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64936. console.log("Button id: " + buttonIdx + "state: ");
  64937. console.dir(state);
  64938. };
  64939. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64940. GenericController.MODEL_FILENAME = 'generic.babylon';
  64941. return GenericController;
  64942. }(BABYLON.WebVRController));
  64943. BABYLON.GenericController = GenericController;
  64944. })(BABYLON || (BABYLON = {}));
  64945. //# sourceMappingURL=babylon.genericController.js.map
  64946. var BABYLON;
  64947. (function (BABYLON) {
  64948. var LoadedMeshInfo = /** @class */ (function () {
  64949. function LoadedMeshInfo() {
  64950. this.buttonMeshes = {};
  64951. this.axisMeshes = {};
  64952. }
  64953. return LoadedMeshInfo;
  64954. }());
  64955. var WindowsMotionController = /** @class */ (function (_super) {
  64956. __extends(WindowsMotionController, _super);
  64957. function WindowsMotionController(vrGamepad) {
  64958. var _this = _super.call(this, vrGamepad) || this;
  64959. _this._mapping = {
  64960. // Semantic button names
  64961. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64962. // A mapping of the button name to glTF model node name
  64963. // that should be transformed by button value.
  64964. buttonMeshNames: {
  64965. 'trigger': 'SELECT',
  64966. 'menu': 'MENU',
  64967. 'grip': 'GRASP',
  64968. 'thumbstick': 'THUMBSTICK_PRESS',
  64969. 'trackpad': 'TOUCHPAD_PRESS'
  64970. },
  64971. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64972. buttonObservableNames: {
  64973. 'trigger': 'onTriggerStateChangedObservable',
  64974. 'menu': 'onSecondaryButtonStateChangedObservable',
  64975. 'grip': 'onMainButtonStateChangedObservable',
  64976. 'thumbstick': 'onPadStateChangedObservable',
  64977. 'trackpad': 'onTrackpadChangedObservable'
  64978. },
  64979. // A mapping of the axis name to glTF model node name
  64980. // that should be transformed by axis value.
  64981. // This array mirrors the browserGamepad.axes array, such that
  64982. // the mesh corresponding to axis 0 is in this array index 0.
  64983. axisMeshNames: [
  64984. 'THUMBSTICK_X',
  64985. 'THUMBSTICK_Y',
  64986. 'TOUCHPAD_TOUCH_X',
  64987. 'TOUCHPAD_TOUCH_Y'
  64988. ],
  64989. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  64990. };
  64991. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64992. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64993. _this.trackpad = { x: 0, y: 0 };
  64994. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64995. _this._loadedMeshInfo = null;
  64996. return _this;
  64997. }
  64998. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64999. get: function () {
  65000. return this.onTriggerStateChangedObservable;
  65001. },
  65002. enumerable: true,
  65003. configurable: true
  65004. });
  65005. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65006. get: function () {
  65007. return this.onSecondaryButtonStateChangedObservable;
  65008. },
  65009. enumerable: true,
  65010. configurable: true
  65011. });
  65012. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65013. get: function () {
  65014. return this.onMainButtonStateChangedObservable;
  65015. },
  65016. enumerable: true,
  65017. configurable: true
  65018. });
  65019. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65020. get: function () {
  65021. return this.onPadStateChangedObservable;
  65022. },
  65023. enumerable: true,
  65024. configurable: true
  65025. });
  65026. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65027. get: function () {
  65028. return this.onTrackpadChangedObservable;
  65029. },
  65030. enumerable: true,
  65031. configurable: true
  65032. });
  65033. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65034. get: function () {
  65035. return this.onTrackpadValuesChangedObservable;
  65036. },
  65037. enumerable: true,
  65038. configurable: true
  65039. });
  65040. /**
  65041. * Called once per frame by the engine.
  65042. */
  65043. WindowsMotionController.prototype.update = function () {
  65044. _super.prototype.update.call(this);
  65045. if (this.browserGamepad.axes) {
  65046. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65047. this.trackpad.x = this.browserGamepad["axes"][2];
  65048. this.trackpad.y = this.browserGamepad["axes"][3];
  65049. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65050. }
  65051. // Only need to animate axes if there is a loaded mesh
  65052. if (this._loadedMeshInfo) {
  65053. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65054. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65055. }
  65056. }
  65057. }
  65058. };
  65059. /**
  65060. * Called once for each button that changed state since the last frame
  65061. * @param buttonIdx Which button index changed
  65062. * @param state New state of the button
  65063. * @param changes Which properties on the state changed since last frame
  65064. */
  65065. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65066. var buttonName = this._mapping.buttons[buttonIdx];
  65067. if (!buttonName) {
  65068. return;
  65069. }
  65070. // Only emit events for buttons that we know how to map from index to name
  65071. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65072. if (observable) {
  65073. observable.notifyObservers(state);
  65074. }
  65075. this.lerpButtonTransform(buttonName, state.value);
  65076. };
  65077. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65078. // If there is no loaded mesh, there is nothing to transform.
  65079. if (!this._loadedMeshInfo) {
  65080. return;
  65081. }
  65082. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65083. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65084. return;
  65085. }
  65086. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65087. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65088. };
  65089. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65090. if (!this._loadedMeshInfo) {
  65091. return;
  65092. }
  65093. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65094. if (!meshInfo) {
  65095. return;
  65096. }
  65097. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65098. return;
  65099. }
  65100. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65101. var lerpValue = axisValue * 0.5 + 0.5;
  65102. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65103. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65104. };
  65105. /**
  65106. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65107. * @param scene scene in which to add meshes
  65108. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65109. */
  65110. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65111. var _this = this;
  65112. if (forceDefault === void 0) { forceDefault = false; }
  65113. var path;
  65114. var filename;
  65115. // Checking if GLB loader is present
  65116. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65117. // Determine the device specific folder based on the ID suffix
  65118. var device = 'default';
  65119. if (this.id && !forceDefault) {
  65120. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65121. device = ((match && match[0]) || device);
  65122. }
  65123. // Hand
  65124. if (this.hand === 'left') {
  65125. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65126. }
  65127. else {
  65128. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65129. }
  65130. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65131. }
  65132. else {
  65133. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65134. path = BABYLON.GenericController.MODEL_BASE_URL;
  65135. filename = BABYLON.GenericController.MODEL_FILENAME;
  65136. }
  65137. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65138. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65139. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65140. if (!_this._loadedMeshInfo) {
  65141. return;
  65142. }
  65143. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65144. _this.attachToMesh(_this._defaultModel);
  65145. if (meshLoaded) {
  65146. meshLoaded(_this._defaultModel);
  65147. }
  65148. }, null, function (scene, message) {
  65149. BABYLON.Tools.Log(message);
  65150. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65151. if (!forceDefault) {
  65152. _this.initControllerMesh(scene, meshLoaded, true);
  65153. }
  65154. });
  65155. };
  65156. /**
  65157. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65158. * can be transformed by button presses and axes values, based on this._mapping.
  65159. *
  65160. * @param scene scene in which the meshes exist
  65161. * @param meshes list of meshes that make up the controller model to process
  65162. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65163. */
  65164. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65165. var loadedMeshInfo = null;
  65166. // Create a new mesh to contain the glTF hierarchy
  65167. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65168. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65169. var childMesh = null;
  65170. for (var i = 0; i < meshes.length; i++) {
  65171. var mesh = meshes[i];
  65172. if (!mesh.parent) {
  65173. // Exclude controller meshes from picking results
  65174. mesh.isPickable = false;
  65175. // Handle root node, attach to the new parentMesh
  65176. childMesh = mesh;
  65177. break;
  65178. }
  65179. }
  65180. if (childMesh) {
  65181. childMesh.setParent(parentMesh);
  65182. // Create our mesh info. Note that this method will always return non-null.
  65183. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65184. }
  65185. else {
  65186. BABYLON.Tools.Warn('Could not find root node in model file.');
  65187. }
  65188. return loadedMeshInfo;
  65189. };
  65190. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65191. var loadedMeshInfo = new LoadedMeshInfo();
  65192. var i;
  65193. loadedMeshInfo.rootNode = rootNode;
  65194. // Reset the caches
  65195. loadedMeshInfo.buttonMeshes = {};
  65196. loadedMeshInfo.axisMeshes = {};
  65197. // Button Meshes
  65198. for (i = 0; i < this._mapping.buttons.length; i++) {
  65199. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65200. if (!buttonMeshName) {
  65201. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65202. continue;
  65203. }
  65204. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65205. if (!buttonMesh) {
  65206. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65207. continue;
  65208. }
  65209. var buttonMeshInfo = {
  65210. index: i,
  65211. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65212. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65213. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65214. };
  65215. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65216. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65217. }
  65218. else {
  65219. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65220. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65221. '(VALUE: ' + !!buttonMeshInfo.value +
  65222. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65223. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65224. ')');
  65225. }
  65226. }
  65227. // Axis Meshes
  65228. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65229. var axisMeshName = this._mapping.axisMeshNames[i];
  65230. if (!axisMeshName) {
  65231. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65232. continue;
  65233. }
  65234. var axisMesh = getChildByName(rootNode, axisMeshName);
  65235. if (!axisMesh) {
  65236. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65237. continue;
  65238. }
  65239. var axisMeshInfo = {
  65240. index: i,
  65241. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65242. min: getImmediateChildByName(axisMesh, 'MIN'),
  65243. max: getImmediateChildByName(axisMesh, 'MAX')
  65244. };
  65245. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65246. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65247. }
  65248. else {
  65249. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65250. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65251. '(VALUE: ' + !!axisMeshInfo.value +
  65252. ', MIN: ' + !!axisMeshInfo.min +
  65253. ', MAX:' + !!axisMeshInfo.max +
  65254. ')');
  65255. }
  65256. }
  65257. // Pointing Ray
  65258. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65259. if (!loadedMeshInfo.pointingPoseNode) {
  65260. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65261. }
  65262. return loadedMeshInfo;
  65263. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65264. function getChildByName(node, name) {
  65265. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65266. }
  65267. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65268. function getImmediateChildByName(node, name) {
  65269. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65270. }
  65271. };
  65272. WindowsMotionController.prototype.getForwardRay = function (length) {
  65273. if (length === void 0) { length = 100; }
  65274. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65275. return _super.prototype.getForwardRay.call(this, length);
  65276. }
  65277. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65278. var origin = m.getTranslation();
  65279. var forward = new BABYLON.Vector3(0, 0, -1);
  65280. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65281. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65282. return new BABYLON.Ray(origin, direction, length);
  65283. };
  65284. WindowsMotionController.prototype.dispose = function () {
  65285. _super.prototype.dispose.call(this);
  65286. this.onTrackpadChangedObservable.clear();
  65287. };
  65288. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65289. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65290. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65291. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65292. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65293. return WindowsMotionController;
  65294. }(BABYLON.WebVRController));
  65295. BABYLON.WindowsMotionController = WindowsMotionController;
  65296. })(BABYLON || (BABYLON = {}));
  65297. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65298. var BABYLON;
  65299. (function (BABYLON) {
  65300. var GearVRController = /** @class */ (function (_super) {
  65301. __extends(GearVRController, _super);
  65302. function GearVRController(vrGamepad) {
  65303. var _this = _super.call(this, vrGamepad) || this;
  65304. _this._buttonIndexToObservableNameMap = [
  65305. 'onTrackpadChangedObservable',
  65306. 'onTriggerStateChangedObservable' // Trigger
  65307. ];
  65308. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65309. return _this;
  65310. }
  65311. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65312. var _this = this;
  65313. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65314. _this._defaultModel = newMeshes[1];
  65315. _this.attachToMesh(_this._defaultModel);
  65316. if (meshLoaded) {
  65317. meshLoaded(_this._defaultModel);
  65318. }
  65319. });
  65320. };
  65321. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65322. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65323. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65324. // Only emit events for buttons that we know how to map from index to observable
  65325. var observable = this[observableName];
  65326. if (observable) {
  65327. observable.notifyObservers(state);
  65328. }
  65329. }
  65330. };
  65331. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65332. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65333. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65334. return GearVRController;
  65335. }(BABYLON.WebVRController));
  65336. BABYLON.GearVRController = GearVRController;
  65337. })(BABYLON || (BABYLON = {}));
  65338. //# sourceMappingURL=babylon.gearVRController.js.map
  65339. var BABYLON;
  65340. (function (BABYLON) {
  65341. /**
  65342. * Google Daydream controller
  65343. */
  65344. var DaydreamController = /** @class */ (function (_super) {
  65345. __extends(DaydreamController, _super);
  65346. function DaydreamController(vrGamepad) {
  65347. var _this = _super.call(this, vrGamepad) || this;
  65348. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65349. return _this;
  65350. }
  65351. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65352. var _this = this;
  65353. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65354. _this._defaultModel = newMeshes[1];
  65355. _this.attachToMesh(_this._defaultModel);
  65356. if (meshLoaded) {
  65357. meshLoaded(_this._defaultModel);
  65358. }
  65359. });
  65360. };
  65361. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65362. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65363. if (buttonIdx === 0) {
  65364. var observable = this.onTriggerStateChangedObservable;
  65365. if (observable) {
  65366. observable.notifyObservers(state);
  65367. }
  65368. }
  65369. else {
  65370. // If the app or home buttons are ever made available
  65371. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65372. }
  65373. };
  65374. /**
  65375. * Base Url for the controller model.
  65376. */
  65377. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65378. /**
  65379. * File name for the controller model.
  65380. */
  65381. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65382. /**
  65383. * Gamepad Id prefix used to identify Daydream Controller.
  65384. */
  65385. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65386. return DaydreamController;
  65387. }(BABYLON.WebVRController));
  65388. BABYLON.DaydreamController = DaydreamController;
  65389. })(BABYLON || (BABYLON = {}));
  65390. //# sourceMappingURL=babylon.daydreamController.js.map
  65391. var BABYLON;
  65392. (function (BABYLON) {
  65393. var FollowCamera = /** @class */ (function (_super) {
  65394. __extends(FollowCamera, _super);
  65395. function FollowCamera(name, position, scene, lockedTarget) {
  65396. if (lockedTarget === void 0) { lockedTarget = null; }
  65397. var _this = _super.call(this, name, position, scene) || this;
  65398. _this.radius = 12;
  65399. _this.rotationOffset = 0;
  65400. _this.heightOffset = 4;
  65401. _this.cameraAcceleration = 0.05;
  65402. _this.maxCameraSpeed = 20;
  65403. _this.lockedTarget = lockedTarget;
  65404. return _this;
  65405. }
  65406. FollowCamera.prototype.getRadians = function (degrees) {
  65407. return degrees * Math.PI / 180;
  65408. };
  65409. FollowCamera.prototype.follow = function (cameraTarget) {
  65410. if (!cameraTarget)
  65411. return;
  65412. var yRotation;
  65413. if (cameraTarget.rotationQuaternion) {
  65414. var rotMatrix = new BABYLON.Matrix();
  65415. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65416. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65417. }
  65418. else {
  65419. yRotation = cameraTarget.rotation.y;
  65420. }
  65421. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65422. var targetPosition = cameraTarget.getAbsolutePosition();
  65423. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65424. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65425. var dx = targetX - this.position.x;
  65426. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65427. var dz = (targetZ) - this.position.z;
  65428. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65429. var vy = dy * this.cameraAcceleration;
  65430. var vz = dz * this.cameraAcceleration * 2;
  65431. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65432. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65433. }
  65434. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65435. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65436. }
  65437. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65438. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65439. }
  65440. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65441. this.setTarget(targetPosition);
  65442. };
  65443. FollowCamera.prototype._checkInputs = function () {
  65444. _super.prototype._checkInputs.call(this);
  65445. if (this.lockedTarget) {
  65446. this.follow(this.lockedTarget);
  65447. }
  65448. };
  65449. FollowCamera.prototype.getClassName = function () {
  65450. return "FollowCamera";
  65451. };
  65452. __decorate([
  65453. BABYLON.serialize()
  65454. ], FollowCamera.prototype, "radius", void 0);
  65455. __decorate([
  65456. BABYLON.serialize()
  65457. ], FollowCamera.prototype, "rotationOffset", void 0);
  65458. __decorate([
  65459. BABYLON.serialize()
  65460. ], FollowCamera.prototype, "heightOffset", void 0);
  65461. __decorate([
  65462. BABYLON.serialize()
  65463. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65464. __decorate([
  65465. BABYLON.serialize()
  65466. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65467. __decorate([
  65468. BABYLON.serializeAsMeshReference("lockedTargetId")
  65469. ], FollowCamera.prototype, "lockedTarget", void 0);
  65470. return FollowCamera;
  65471. }(BABYLON.TargetCamera));
  65472. BABYLON.FollowCamera = FollowCamera;
  65473. var ArcFollowCamera = /** @class */ (function (_super) {
  65474. __extends(ArcFollowCamera, _super);
  65475. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65476. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65477. _this.alpha = alpha;
  65478. _this.beta = beta;
  65479. _this.radius = radius;
  65480. _this.target = target;
  65481. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65482. _this.follow();
  65483. return _this;
  65484. }
  65485. ArcFollowCamera.prototype.follow = function () {
  65486. if (!this.target) {
  65487. return;
  65488. }
  65489. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65490. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65491. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65492. var targetPosition = this.target.getAbsolutePosition();
  65493. this.position = targetPosition.add(this._cartesianCoordinates);
  65494. this.setTarget(targetPosition);
  65495. };
  65496. ArcFollowCamera.prototype._checkInputs = function () {
  65497. _super.prototype._checkInputs.call(this);
  65498. this.follow();
  65499. };
  65500. ArcFollowCamera.prototype.getClassName = function () {
  65501. return "ArcFollowCamera";
  65502. };
  65503. return ArcFollowCamera;
  65504. }(BABYLON.TargetCamera));
  65505. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65506. })(BABYLON || (BABYLON = {}));
  65507. //# sourceMappingURL=babylon.followCamera.js.map
  65508. var BABYLON;
  65509. (function (BABYLON) {
  65510. // We're mainly based on the logic defined into the FreeCamera code
  65511. var UniversalCamera = /** @class */ (function (_super) {
  65512. __extends(UniversalCamera, _super);
  65513. //-- end properties for backward compatibility for inputs
  65514. function UniversalCamera(name, position, scene) {
  65515. var _this = _super.call(this, name, position, scene) || this;
  65516. _this.inputs.addGamepad();
  65517. return _this;
  65518. }
  65519. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65520. //-- Begin properties for backward compatibility for inputs
  65521. get: function () {
  65522. var gamepad = this.inputs.attached["gamepad"];
  65523. if (gamepad)
  65524. return gamepad.gamepadAngularSensibility;
  65525. return 0;
  65526. },
  65527. set: function (value) {
  65528. var gamepad = this.inputs.attached["gamepad"];
  65529. if (gamepad)
  65530. gamepad.gamepadAngularSensibility = value;
  65531. },
  65532. enumerable: true,
  65533. configurable: true
  65534. });
  65535. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65536. get: function () {
  65537. var gamepad = this.inputs.attached["gamepad"];
  65538. if (gamepad)
  65539. return gamepad.gamepadMoveSensibility;
  65540. return 0;
  65541. },
  65542. set: function (value) {
  65543. var gamepad = this.inputs.attached["gamepad"];
  65544. if (gamepad)
  65545. gamepad.gamepadMoveSensibility = value;
  65546. },
  65547. enumerable: true,
  65548. configurable: true
  65549. });
  65550. UniversalCamera.prototype.getClassName = function () {
  65551. return "UniversalCamera";
  65552. };
  65553. return UniversalCamera;
  65554. }(BABYLON.TouchCamera));
  65555. BABYLON.UniversalCamera = UniversalCamera;
  65556. })(BABYLON || (BABYLON = {}));
  65557. //# sourceMappingURL=babylon.universalCamera.js.map
  65558. var BABYLON;
  65559. (function (BABYLON) {
  65560. // We're mainly based on the logic defined into the FreeCamera code
  65561. var GamepadCamera = /** @class */ (function (_super) {
  65562. __extends(GamepadCamera, _super);
  65563. //-- end properties for backward compatibility for inputs
  65564. function GamepadCamera(name, position, scene) {
  65565. return _super.call(this, name, position, scene) || this;
  65566. }
  65567. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65568. //-- Begin properties for backward compatibility for inputs
  65569. get: function () {
  65570. var gamepad = this.inputs.attached["gamepad"];
  65571. if (gamepad)
  65572. return gamepad.gamepadAngularSensibility;
  65573. return 0;
  65574. },
  65575. set: function (value) {
  65576. var gamepad = this.inputs.attached["gamepad"];
  65577. if (gamepad)
  65578. gamepad.gamepadAngularSensibility = value;
  65579. },
  65580. enumerable: true,
  65581. configurable: true
  65582. });
  65583. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65584. get: function () {
  65585. var gamepad = this.inputs.attached["gamepad"];
  65586. if (gamepad)
  65587. return gamepad.gamepadMoveSensibility;
  65588. return 0;
  65589. },
  65590. set: function (value) {
  65591. var gamepad = this.inputs.attached["gamepad"];
  65592. if (gamepad)
  65593. gamepad.gamepadMoveSensibility = value;
  65594. },
  65595. enumerable: true,
  65596. configurable: true
  65597. });
  65598. GamepadCamera.prototype.getClassName = function () {
  65599. return "GamepadCamera";
  65600. };
  65601. return GamepadCamera;
  65602. }(BABYLON.UniversalCamera));
  65603. BABYLON.GamepadCamera = GamepadCamera;
  65604. })(BABYLON || (BABYLON = {}));
  65605. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65606. var BABYLON;
  65607. (function (BABYLON) {
  65608. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65609. function PostProcessRenderPipelineManager() {
  65610. this._renderPipelines = {};
  65611. }
  65612. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65613. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65614. };
  65615. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65616. if (unique === void 0) { unique = false; }
  65617. var renderPipeline = this._renderPipelines[renderPipelineName];
  65618. if (!renderPipeline) {
  65619. return;
  65620. }
  65621. renderPipeline._attachCameras(cameras, unique);
  65622. };
  65623. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65624. var renderPipeline = this._renderPipelines[renderPipelineName];
  65625. if (!renderPipeline) {
  65626. return;
  65627. }
  65628. renderPipeline._detachCameras(cameras);
  65629. };
  65630. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65631. var renderPipeline = this._renderPipelines[renderPipelineName];
  65632. if (!renderPipeline) {
  65633. return;
  65634. }
  65635. renderPipeline._enableEffect(renderEffectName, cameras);
  65636. };
  65637. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65638. var renderPipeline = this._renderPipelines[renderPipelineName];
  65639. if (!renderPipeline) {
  65640. return;
  65641. }
  65642. renderPipeline._disableEffect(renderEffectName, cameras);
  65643. };
  65644. PostProcessRenderPipelineManager.prototype.update = function () {
  65645. for (var renderPipelineName in this._renderPipelines) {
  65646. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65647. var pipeline = this._renderPipelines[renderPipelineName];
  65648. if (!pipeline.isSupported) {
  65649. pipeline.dispose();
  65650. delete this._renderPipelines[renderPipelineName];
  65651. }
  65652. else {
  65653. pipeline._update();
  65654. }
  65655. }
  65656. }
  65657. };
  65658. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65659. for (var renderPipelineName in this._renderPipelines) {
  65660. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65661. var pipeline = this._renderPipelines[renderPipelineName];
  65662. pipeline._rebuild();
  65663. }
  65664. }
  65665. };
  65666. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65667. for (var renderPipelineName in this._renderPipelines) {
  65668. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65669. var pipeline = this._renderPipelines[renderPipelineName];
  65670. pipeline.dispose();
  65671. }
  65672. }
  65673. };
  65674. return PostProcessRenderPipelineManager;
  65675. }());
  65676. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65677. })(BABYLON || (BABYLON = {}));
  65678. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65679. var BABYLON;
  65680. (function (BABYLON) {
  65681. /**
  65682. * This represents a set of one or more post processes in Babylon.
  65683. * A post process can be used to apply a shader to a texture after it is rendered.
  65684. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65685. */
  65686. var PostProcessRenderEffect = /** @class */ (function () {
  65687. /**
  65688. * Instantiates a post process render effect.
  65689. * A post process can be used to apply a shader to a texture after it is rendered.
  65690. * @param engine The engine the effect is tied to
  65691. * @param name The name of the effect
  65692. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65693. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65694. */
  65695. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65696. this._name = name;
  65697. this._singleInstance = singleInstance || true;
  65698. this._getPostProcesses = getPostProcesses;
  65699. this._cameras = {};
  65700. this._indicesForCamera = {};
  65701. this._postProcesses = {};
  65702. }
  65703. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65704. /**
  65705. * Checks if all the post processes in the effect are supported.
  65706. */
  65707. get: function () {
  65708. for (var index in this._postProcesses) {
  65709. for (var ppIndex in this._postProcesses[index]) {
  65710. if (!this._postProcesses[index][ppIndex].isSupported) {
  65711. return false;
  65712. }
  65713. }
  65714. }
  65715. return true;
  65716. },
  65717. enumerable: true,
  65718. configurable: true
  65719. });
  65720. /**
  65721. * Updates the current state of the effect
  65722. */
  65723. PostProcessRenderEffect.prototype._update = function () {
  65724. };
  65725. /**
  65726. * Attaches the effect on cameras
  65727. * @param cameras The camera to attach to.
  65728. */
  65729. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65730. var _this = this;
  65731. var cameraKey;
  65732. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65733. if (!cams) {
  65734. return;
  65735. }
  65736. for (var i = 0; i < cams.length; i++) {
  65737. var camera = cams[i];
  65738. var cameraName = camera.name;
  65739. if (this._singleInstance) {
  65740. cameraKey = 0;
  65741. }
  65742. else {
  65743. cameraKey = cameraName;
  65744. }
  65745. if (!this._postProcesses[cameraKey]) {
  65746. var postProcess = this._getPostProcesses();
  65747. if (postProcess) {
  65748. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65749. }
  65750. }
  65751. if (!this._indicesForCamera[cameraName]) {
  65752. this._indicesForCamera[cameraName] = [];
  65753. }
  65754. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65755. var index = camera.attachPostProcess(postProcess);
  65756. _this._indicesForCamera[cameraName].push(index);
  65757. });
  65758. if (!this._cameras[cameraName]) {
  65759. this._cameras[cameraName] = camera;
  65760. }
  65761. }
  65762. };
  65763. /**
  65764. * Detatches the effect on cameras
  65765. * @param cameras The camera to detatch from.
  65766. */
  65767. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65768. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65769. if (!cams) {
  65770. return;
  65771. }
  65772. for (var i = 0; i < cams.length; i++) {
  65773. var camera = cams[i];
  65774. var cameraName = camera.name;
  65775. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65776. camera.detachPostProcess(postProcess);
  65777. });
  65778. if (this._cameras[cameraName]) {
  65779. //this._indicesForCamera.splice(index, 1);
  65780. this._cameras[cameraName] = null;
  65781. }
  65782. }
  65783. };
  65784. /**
  65785. * Enables the effect on given cameras
  65786. * @param cameras The camera to enable.
  65787. */
  65788. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65789. var _this = this;
  65790. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65791. if (!cams) {
  65792. return;
  65793. }
  65794. for (var i = 0; i < cams.length; i++) {
  65795. var camera = cams[i];
  65796. var cameraName = camera.name;
  65797. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65798. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65799. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65800. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65801. });
  65802. }
  65803. }
  65804. }
  65805. };
  65806. /**
  65807. * Disables the effect on the given cameras
  65808. * @param cameras The camera to disable.
  65809. */
  65810. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65811. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65812. if (!cams) {
  65813. return;
  65814. }
  65815. for (var i = 0; i < cams.length; i++) {
  65816. var camera = cams[i];
  65817. var cameraName = camera.name;
  65818. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65819. camera.detachPostProcess(postProcess);
  65820. });
  65821. }
  65822. };
  65823. /**
  65824. * Gets a list of the post processes contained in the effect.
  65825. * @param camera The camera to get the post processes on.
  65826. * @returns The list of the post processes in the effect.
  65827. */
  65828. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65829. if (this._singleInstance) {
  65830. return this._postProcesses[0];
  65831. }
  65832. else {
  65833. if (!camera) {
  65834. return null;
  65835. }
  65836. return this._postProcesses[camera.name];
  65837. }
  65838. };
  65839. return PostProcessRenderEffect;
  65840. }());
  65841. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65842. })(BABYLON || (BABYLON = {}));
  65843. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65844. var BABYLON;
  65845. (function (BABYLON) {
  65846. var PostProcessRenderPipeline = /** @class */ (function () {
  65847. function PostProcessRenderPipeline(engine, name) {
  65848. this.engine = engine;
  65849. this._name = name;
  65850. this._renderEffects = {};
  65851. this._renderEffectsForIsolatedPass = new Array();
  65852. this._cameras = [];
  65853. }
  65854. PostProcessRenderPipeline.prototype.getClassName = function () {
  65855. return "PostProcessRenderPipeline";
  65856. };
  65857. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65858. get: function () {
  65859. for (var renderEffectName in this._renderEffects) {
  65860. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65861. if (!this._renderEffects[renderEffectName].isSupported) {
  65862. return false;
  65863. }
  65864. }
  65865. }
  65866. return true;
  65867. },
  65868. enumerable: true,
  65869. configurable: true
  65870. });
  65871. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65872. this._renderEffects[renderEffect._name] = renderEffect;
  65873. };
  65874. // private
  65875. PostProcessRenderPipeline.prototype._rebuild = function () {
  65876. };
  65877. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65878. var renderEffects = this._renderEffects[renderEffectName];
  65879. if (!renderEffects) {
  65880. return;
  65881. }
  65882. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65883. };
  65884. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65885. var renderEffects = this._renderEffects[renderEffectName];
  65886. if (!renderEffects) {
  65887. return;
  65888. }
  65889. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65890. };
  65891. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65892. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65893. if (!cams) {
  65894. return;
  65895. }
  65896. var indicesToDelete = [];
  65897. var i;
  65898. for (i = 0; i < cams.length; i++) {
  65899. var camera = cams[i];
  65900. var cameraName = camera.name;
  65901. if (this._cameras.indexOf(camera) === -1) {
  65902. this._cameras[cameraName] = camera;
  65903. }
  65904. else if (unique) {
  65905. indicesToDelete.push(i);
  65906. }
  65907. }
  65908. for (i = 0; i < indicesToDelete.length; i++) {
  65909. cameras.splice(indicesToDelete[i], 1);
  65910. }
  65911. for (var renderEffectName in this._renderEffects) {
  65912. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65913. this._renderEffects[renderEffectName]._attachCameras(cams);
  65914. }
  65915. }
  65916. };
  65917. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65918. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65919. if (!cams) {
  65920. return;
  65921. }
  65922. for (var renderEffectName in this._renderEffects) {
  65923. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65924. this._renderEffects[renderEffectName]._detachCameras(cams);
  65925. }
  65926. }
  65927. for (var i = 0; i < cams.length; i++) {
  65928. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65929. }
  65930. };
  65931. PostProcessRenderPipeline.prototype._update = function () {
  65932. for (var renderEffectName in this._renderEffects) {
  65933. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65934. this._renderEffects[renderEffectName]._update();
  65935. }
  65936. }
  65937. for (var i = 0; i < this._cameras.length; i++) {
  65938. var cameraName = this._cameras[i].name;
  65939. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65940. this._renderEffectsForIsolatedPass[cameraName]._update();
  65941. }
  65942. }
  65943. };
  65944. PostProcessRenderPipeline.prototype._reset = function () {
  65945. this._renderEffects = {};
  65946. this._renderEffectsForIsolatedPass = new Array();
  65947. };
  65948. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  65949. // 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)
  65950. var effectKeys = Object.keys(this._renderEffects);
  65951. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  65952. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  65953. if (postProcesses) {
  65954. postProcesses[0].samples = 4;
  65955. return true;
  65956. }
  65957. }
  65958. return false;
  65959. };
  65960. PostProcessRenderPipeline.prototype.dispose = function () {
  65961. // Must be implemented by children
  65962. };
  65963. __decorate([
  65964. BABYLON.serialize()
  65965. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65966. return PostProcessRenderPipeline;
  65967. }());
  65968. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65969. })(BABYLON || (BABYLON = {}));
  65970. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65971. var BABYLON;
  65972. (function (BABYLON) {
  65973. /**
  65974. * This represents a depth renderer in Babylon.
  65975. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  65976. */
  65977. var DepthRenderer = /** @class */ (function () {
  65978. /**
  65979. * Instantiates a depth renderer
  65980. * @param scene The scene the renderer belongs to
  65981. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  65982. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  65983. */
  65984. function DepthRenderer(scene, type, camera) {
  65985. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65986. if (camera === void 0) { camera = null; }
  65987. var _this = this;
  65988. this._scene = scene;
  65989. this._camera = camera;
  65990. var engine = scene.getEngine();
  65991. // Render target
  65992. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65993. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65994. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65995. this._depthMap.refreshRate = 1;
  65996. this._depthMap.renderParticles = false;
  65997. this._depthMap.renderList = null;
  65998. // Camera to get depth map from to support multiple concurrent cameras
  65999. this._depthMap.activeCamera = this._camera;
  66000. this._depthMap.ignoreCameraViewport = true;
  66001. this._depthMap.useCameraPostProcesses = false;
  66002. // set default depth value to 1.0 (far away)
  66003. this._depthMap.onClearObservable.add(function (engine) {
  66004. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66005. });
  66006. // Custom render function
  66007. var renderSubMesh = function (subMesh) {
  66008. var mesh = subMesh.getRenderingMesh();
  66009. var scene = _this._scene;
  66010. var engine = scene.getEngine();
  66011. var material = subMesh.getMaterial();
  66012. if (!material) {
  66013. return;
  66014. }
  66015. // Culling and reverse (right handed system)
  66016. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66017. // Managing instances
  66018. var batch = mesh._getInstancesRenderList(subMesh._id);
  66019. if (batch.mustReturn) {
  66020. return;
  66021. }
  66022. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66023. var camera = _this._camera || scene.activeCamera;
  66024. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66025. engine.enableEffect(_this._effect);
  66026. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66027. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66028. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66029. // Alpha test
  66030. if (material && material.needAlphaTesting()) {
  66031. var alphaTexture = material.getAlphaTestTexture();
  66032. if (alphaTexture) {
  66033. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66034. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66035. }
  66036. }
  66037. // Bones
  66038. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66039. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66040. }
  66041. // Draw
  66042. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66043. }
  66044. };
  66045. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66046. var index;
  66047. if (depthOnlySubMeshes.length) {
  66048. engine.setColorWrite(false);
  66049. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66050. renderSubMesh(depthOnlySubMeshes.data[index]);
  66051. }
  66052. engine.setColorWrite(true);
  66053. }
  66054. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66055. renderSubMesh(opaqueSubMeshes.data[index]);
  66056. }
  66057. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66058. renderSubMesh(alphaTestSubMeshes.data[index]);
  66059. }
  66060. };
  66061. }
  66062. /**
  66063. * Creates the depth rendering effect and checks if the effect is ready.
  66064. * @param subMesh The submesh to be used to render the depth map of
  66065. * @param useInstances If multiple world instances should be used
  66066. * @returns if the depth renderer is ready to render the depth map
  66067. */
  66068. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66069. var material = subMesh.getMaterial();
  66070. if (material.disableDepthWrite) {
  66071. return false;
  66072. }
  66073. var defines = [];
  66074. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66075. var mesh = subMesh.getMesh();
  66076. // Alpha test
  66077. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66078. defines.push("#define ALPHATEST");
  66079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66080. attribs.push(BABYLON.VertexBuffer.UVKind);
  66081. defines.push("#define UV1");
  66082. }
  66083. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66084. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66085. defines.push("#define UV2");
  66086. }
  66087. }
  66088. // Bones
  66089. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66090. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66091. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66092. if (mesh.numBoneInfluencers > 4) {
  66093. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66094. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66095. }
  66096. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66097. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66098. }
  66099. else {
  66100. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66101. }
  66102. // Instances
  66103. if (useInstances) {
  66104. defines.push("#define INSTANCES");
  66105. attribs.push("world0");
  66106. attribs.push("world1");
  66107. attribs.push("world2");
  66108. attribs.push("world3");
  66109. }
  66110. // Get correct effect
  66111. var join = defines.join("\n");
  66112. if (this._cachedDefines !== join) {
  66113. this._cachedDefines = join;
  66114. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66115. }
  66116. return this._effect.isReady();
  66117. };
  66118. /**
  66119. * Gets the texture which the depth map will be written to.
  66120. * @returns The depth map texture
  66121. */
  66122. DepthRenderer.prototype.getDepthMap = function () {
  66123. return this._depthMap;
  66124. };
  66125. /**
  66126. * Disposes of the depth renderer.
  66127. */
  66128. DepthRenderer.prototype.dispose = function () {
  66129. this._depthMap.dispose();
  66130. };
  66131. return DepthRenderer;
  66132. }());
  66133. BABYLON.DepthRenderer = DepthRenderer;
  66134. })(BABYLON || (BABYLON = {}));
  66135. //# sourceMappingURL=babylon.depthRenderer.js.map
  66136. var BABYLON;
  66137. (function (BABYLON) {
  66138. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66139. __extends(SSAORenderingPipeline, _super);
  66140. /**
  66141. * @constructor
  66142. * @param {string} name - The rendering pipeline name
  66143. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66144. * @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 }
  66145. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66146. */
  66147. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66148. var _this = _super.call(this, scene.getEngine(), name) || this;
  66149. // Members
  66150. /**
  66151. * The PassPostProcess id in the pipeline that contains the original scene color
  66152. * @type {string}
  66153. */
  66154. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66155. /**
  66156. * The SSAO PostProcess id in the pipeline
  66157. * @type {string}
  66158. */
  66159. _this.SSAORenderEffect = "SSAORenderEffect";
  66160. /**
  66161. * The horizontal blur PostProcess id in the pipeline
  66162. * @type {string}
  66163. */
  66164. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66165. /**
  66166. * The vertical blur PostProcess id in the pipeline
  66167. * @type {string}
  66168. */
  66169. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66170. /**
  66171. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66172. * @type {string}
  66173. */
  66174. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66175. /**
  66176. * The output strength of the SSAO post-process. Default value is 1.0.
  66177. * @type {number}
  66178. */
  66179. _this.totalStrength = 1.0;
  66180. /**
  66181. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66182. * @type {number}
  66183. */
  66184. _this.radius = 0.0001;
  66185. /**
  66186. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66187. * Must not be equal to fallOff and superior to fallOff.
  66188. * Default value is 0.975
  66189. * @type {number}
  66190. */
  66191. _this.area = 0.0075;
  66192. /**
  66193. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66194. * Must not be equal to area and inferior to area.
  66195. * Default value is 0.0
  66196. * @type {number}
  66197. */
  66198. _this.fallOff = 0.000001;
  66199. /**
  66200. * The base color of the SSAO post-process
  66201. * The final result is "base + ssao" between [0, 1]
  66202. * @type {number}
  66203. */
  66204. _this.base = 0.5;
  66205. _this._firstUpdate = true;
  66206. _this._scene = scene;
  66207. // Set up assets
  66208. _this._createRandomTexture();
  66209. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66210. var ssaoRatio = ratio.ssaoRatio || ratio;
  66211. var combineRatio = ratio.combineRatio || ratio;
  66212. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66213. _this._createSSAOPostProcess(ssaoRatio);
  66214. _this._createBlurPostProcess(ssaoRatio);
  66215. _this._createSSAOCombinePostProcess(combineRatio);
  66216. // Set up pipeline
  66217. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66218. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66219. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66220. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66221. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66222. // Finish
  66223. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66224. if (cameras)
  66225. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66226. return _this;
  66227. }
  66228. // Public Methods
  66229. /**
  66230. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66231. */
  66232. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66233. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66234. for (var i = 0; i < this._scene.cameras.length; i++) {
  66235. var camera = this._scene.cameras[i];
  66236. this._originalColorPostProcess.dispose(camera);
  66237. this._ssaoPostProcess.dispose(camera);
  66238. this._blurHPostProcess.dispose(camera);
  66239. this._blurVPostProcess.dispose(camera);
  66240. this._ssaoCombinePostProcess.dispose(camera);
  66241. }
  66242. this._randomTexture.dispose();
  66243. if (disableDepthRender)
  66244. this._scene.disableDepthRenderer();
  66245. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66246. _super.prototype.dispose.call(this);
  66247. };
  66248. // Private Methods
  66249. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66250. var _this = this;
  66251. var size = 16;
  66252. 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);
  66253. 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);
  66254. this._blurHPostProcess.onActivateObservable.add(function () {
  66255. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66256. _this._blurHPostProcess.kernel = size * dw;
  66257. });
  66258. this._blurVPostProcess.onActivateObservable.add(function () {
  66259. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66260. _this._blurVPostProcess.kernel = size * dw;
  66261. });
  66262. };
  66263. SSAORenderingPipeline.prototype._rebuild = function () {
  66264. this._firstUpdate = true;
  66265. _super.prototype._rebuild.call(this);
  66266. };
  66267. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66268. var _this = this;
  66269. var numSamples = 16;
  66270. var sampleSphere = [
  66271. 0.5381, 0.1856, -0.4319,
  66272. 0.1379, 0.2486, 0.4430,
  66273. 0.3371, 0.5679, -0.0057,
  66274. -0.6999, -0.0451, -0.0019,
  66275. 0.0689, -0.1598, -0.8547,
  66276. 0.0560, 0.0069, -0.1843,
  66277. -0.0146, 0.1402, 0.0762,
  66278. 0.0100, -0.1924, -0.0344,
  66279. -0.3577, -0.5301, -0.4358,
  66280. -0.3169, 0.1063, 0.0158,
  66281. 0.0103, -0.5869, 0.0046,
  66282. -0.0897, -0.4940, 0.3287,
  66283. 0.7119, -0.0154, -0.0918,
  66284. -0.0533, 0.0596, -0.5411,
  66285. 0.0352, -0.0631, 0.5460,
  66286. -0.4776, 0.2847, -0.0271
  66287. ];
  66288. var samplesFactor = 1.0 / numSamples;
  66289. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66290. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66291. "area", "fallOff", "base", "range", "viewport"
  66292. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66293. this._ssaoPostProcess.onApply = function (effect) {
  66294. if (_this._firstUpdate) {
  66295. effect.setArray3("sampleSphere", sampleSphere);
  66296. effect.setFloat("samplesFactor", samplesFactor);
  66297. effect.setFloat("randTextureTiles", 4.0);
  66298. }
  66299. effect.setFloat("totalStrength", _this.totalStrength);
  66300. effect.setFloat("radius", _this.radius);
  66301. effect.setFloat("area", _this.area);
  66302. effect.setFloat("fallOff", _this.fallOff);
  66303. effect.setFloat("base", _this.base);
  66304. effect.setTexture("textureSampler", _this._depthTexture);
  66305. effect.setTexture("randomSampler", _this._randomTexture);
  66306. };
  66307. };
  66308. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66309. var _this = this;
  66310. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66311. this._ssaoCombinePostProcess.onApply = function (effect) {
  66312. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66313. };
  66314. };
  66315. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66316. var size = 512;
  66317. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66318. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66319. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66320. var context = this._randomTexture.getContext();
  66321. var rand = function (min, max) {
  66322. return Math.random() * (max - min) + min;
  66323. };
  66324. var randVector = BABYLON.Vector3.Zero();
  66325. for (var x = 0; x < size; x++) {
  66326. for (var y = 0; y < size; y++) {
  66327. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66328. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66329. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66330. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66331. context.fillRect(x, y, 1, 1);
  66332. }
  66333. }
  66334. this._randomTexture.update(false);
  66335. };
  66336. __decorate([
  66337. BABYLON.serialize()
  66338. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66339. __decorate([
  66340. BABYLON.serialize()
  66341. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66342. __decorate([
  66343. BABYLON.serialize()
  66344. ], SSAORenderingPipeline.prototype, "area", void 0);
  66345. __decorate([
  66346. BABYLON.serialize()
  66347. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66348. __decorate([
  66349. BABYLON.serialize()
  66350. ], SSAORenderingPipeline.prototype, "base", void 0);
  66351. return SSAORenderingPipeline;
  66352. }(BABYLON.PostProcessRenderPipeline));
  66353. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66354. })(BABYLON || (BABYLON = {}));
  66355. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66356. var BABYLON;
  66357. (function (BABYLON) {
  66358. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66359. __extends(SSAO2RenderingPipeline, _super);
  66360. /**
  66361. * @constructor
  66362. * @param {string} name - The rendering pipeline name
  66363. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66364. * @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 }
  66365. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66366. */
  66367. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66368. var _this = _super.call(this, scene.getEngine(), name) || this;
  66369. // Members
  66370. /**
  66371. * The PassPostProcess id in the pipeline that contains the original scene color
  66372. * @type {string}
  66373. */
  66374. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66375. /**
  66376. * The SSAO PostProcess id in the pipeline
  66377. * @type {string}
  66378. */
  66379. _this.SSAORenderEffect = "SSAORenderEffect";
  66380. /**
  66381. * The horizontal blur PostProcess id in the pipeline
  66382. * @type {string}
  66383. */
  66384. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66385. /**
  66386. * The vertical blur PostProcess id in the pipeline
  66387. * @type {string}
  66388. */
  66389. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66390. /**
  66391. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66392. * @type {string}
  66393. */
  66394. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66395. /**
  66396. * The output strength of the SSAO post-process. Default value is 1.0.
  66397. * @type {number}
  66398. */
  66399. _this.totalStrength = 1.0;
  66400. /**
  66401. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66402. * @type {number}
  66403. */
  66404. _this.maxZ = 100.0;
  66405. /**
  66406. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66407. * @type {number}
  66408. */
  66409. _this.minZAspect = 0.2;
  66410. /**
  66411. * Number of samples used for the SSAO calculations. Default value is 8
  66412. * @type {number}
  66413. */
  66414. _this._samples = 8;
  66415. /**
  66416. * Are we using bilateral blur ?
  66417. * @type {boolean}
  66418. */
  66419. _this._expensiveBlur = true;
  66420. /**
  66421. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66422. * @type {number}
  66423. */
  66424. _this.radius = 2.0;
  66425. /**
  66426. * The base color of the SSAO post-process
  66427. * The final result is "base + ssao" between [0, 1]
  66428. * @type {number}
  66429. */
  66430. _this.base = 0.1;
  66431. _this._firstUpdate = true;
  66432. _this._scene = scene;
  66433. if (!_this.isSupported) {
  66434. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66435. return _this;
  66436. }
  66437. var ssaoRatio = ratio.ssaoRatio || ratio;
  66438. var blurRatio = ratio.blurRatio || ratio;
  66439. // Set up assets
  66440. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66441. _this._createRandomTexture();
  66442. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66443. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66444. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66445. _this._createSSAOPostProcess(1.0);
  66446. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66447. _this._createSSAOCombinePostProcess(blurRatio);
  66448. // Set up pipeline
  66449. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66450. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66451. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66452. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66453. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66454. // Finish
  66455. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66456. if (cameras)
  66457. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66458. return _this;
  66459. }
  66460. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66461. get: function () {
  66462. return this._samples;
  66463. },
  66464. set: function (n) {
  66465. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66466. this._samples = n;
  66467. this._sampleSphere = this._generateHemisphere();
  66468. this._firstUpdate = true;
  66469. },
  66470. enumerable: true,
  66471. configurable: true
  66472. });
  66473. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66474. get: function () {
  66475. return this._expensiveBlur;
  66476. },
  66477. set: function (b) {
  66478. 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"]);
  66479. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66480. this._expensiveBlur = b;
  66481. this._firstUpdate = true;
  66482. },
  66483. enumerable: true,
  66484. configurable: true
  66485. });
  66486. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66487. /**
  66488. * Support test.
  66489. * @type {boolean}
  66490. */
  66491. get: function () {
  66492. var engine = BABYLON.Engine.LastCreatedEngine;
  66493. if (!engine) {
  66494. return false;
  66495. }
  66496. return engine.getCaps().drawBuffersExtension;
  66497. },
  66498. enumerable: true,
  66499. configurable: true
  66500. });
  66501. // Public Methods
  66502. /**
  66503. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66504. */
  66505. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66506. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66507. for (var i = 0; i < this._scene.cameras.length; i++) {
  66508. var camera = this._scene.cameras[i];
  66509. this._originalColorPostProcess.dispose(camera);
  66510. this._ssaoPostProcess.dispose(camera);
  66511. this._blurHPostProcess.dispose(camera);
  66512. this._blurVPostProcess.dispose(camera);
  66513. this._ssaoCombinePostProcess.dispose(camera);
  66514. }
  66515. this._randomTexture.dispose();
  66516. if (disableGeometryBufferRenderer)
  66517. this._scene.disableGeometryBufferRenderer();
  66518. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66519. _super.prototype.dispose.call(this);
  66520. };
  66521. // Private Methods
  66522. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66523. var _this = this;
  66524. this._samplerOffsets = [];
  66525. var expensive = this.expensiveBlur;
  66526. for (var i = -8; i < 8; i++) {
  66527. this._samplerOffsets.push(i * 2 + 0.5);
  66528. }
  66529. 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");
  66530. this._blurHPostProcess.onApply = function (effect) {
  66531. if (!_this._scene.activeCamera) {
  66532. return;
  66533. }
  66534. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66535. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66536. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66537. effect.setFloat("radius", _this.radius);
  66538. effect.setTexture("depthSampler", _this._depthTexture);
  66539. if (_this._firstUpdate) {
  66540. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66541. }
  66542. };
  66543. 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");
  66544. this._blurVPostProcess.onApply = function (effect) {
  66545. if (!_this._scene.activeCamera) {
  66546. return;
  66547. }
  66548. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66549. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66550. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66551. effect.setFloat("radius", _this.radius);
  66552. effect.setTexture("depthSampler", _this._depthTexture);
  66553. if (_this._firstUpdate) {
  66554. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66555. _this._firstUpdate = false;
  66556. }
  66557. };
  66558. };
  66559. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66560. this._firstUpdate = true;
  66561. _super.prototype._rebuild.call(this);
  66562. };
  66563. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66564. var numSamples = this.samples;
  66565. var result = [];
  66566. var vector, scale;
  66567. var rand = function (min, max) {
  66568. return Math.random() * (max - min) + min;
  66569. };
  66570. var i = 0;
  66571. while (i < numSamples) {
  66572. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66573. vector.normalize();
  66574. scale = i / numSamples;
  66575. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66576. vector.scaleInPlace(scale);
  66577. result.push(vector.x, vector.y, vector.z);
  66578. i++;
  66579. }
  66580. return result;
  66581. };
  66582. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66583. var _this = this;
  66584. var numSamples = this.samples;
  66585. this._sampleSphere = this._generateHemisphere();
  66586. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66587. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66588. "base", "range", "projection", "near", "far", "texelSize",
  66589. "xViewport", "yViewport", "maxZ", "minZAspect"
  66590. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66591. this._ssaoPostProcess.onApply = function (effect) {
  66592. if (_this._firstUpdate) {
  66593. effect.setArray3("sampleSphere", _this._sampleSphere);
  66594. effect.setFloat("randTextureTiles", 4.0);
  66595. }
  66596. if (!_this._scene.activeCamera) {
  66597. return;
  66598. }
  66599. effect.setFloat("samplesFactor", 1 / _this.samples);
  66600. effect.setFloat("totalStrength", _this.totalStrength);
  66601. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66602. effect.setFloat("radius", _this.radius);
  66603. effect.setFloat("maxZ", _this.maxZ);
  66604. effect.setFloat("minZAspect", _this.minZAspect);
  66605. effect.setFloat("base", _this.base);
  66606. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66607. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66608. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66609. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66610. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66611. effect.setTexture("textureSampler", _this._depthTexture);
  66612. effect.setTexture("normalSampler", _this._normalTexture);
  66613. effect.setTexture("randomSampler", _this._randomTexture);
  66614. };
  66615. };
  66616. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66617. var _this = this;
  66618. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66619. this._ssaoCombinePostProcess.onApply = function (effect) {
  66620. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66621. };
  66622. };
  66623. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66624. var size = 512;
  66625. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66626. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66627. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66628. var context = this._randomTexture.getContext();
  66629. var rand = function (min, max) {
  66630. return Math.random() * (max - min) + min;
  66631. };
  66632. var randVector = BABYLON.Vector3.Zero();
  66633. for (var x = 0; x < size; x++) {
  66634. for (var y = 0; y < size; y++) {
  66635. randVector.x = rand(0.0, 1.0);
  66636. randVector.y = rand(0.0, 1.0);
  66637. randVector.z = 0.0;
  66638. randVector.normalize();
  66639. randVector.scaleInPlace(255);
  66640. randVector.x = Math.floor(randVector.x);
  66641. randVector.y = Math.floor(randVector.y);
  66642. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66643. context.fillRect(x, y, 1, 1);
  66644. }
  66645. }
  66646. this._randomTexture.update(false);
  66647. };
  66648. __decorate([
  66649. BABYLON.serialize()
  66650. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66651. __decorate([
  66652. BABYLON.serialize()
  66653. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66654. __decorate([
  66655. BABYLON.serialize()
  66656. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66657. __decorate([
  66658. BABYLON.serialize("samples")
  66659. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66660. __decorate([
  66661. BABYLON.serialize("expensiveBlur")
  66662. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66663. __decorate([
  66664. BABYLON.serialize()
  66665. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66666. __decorate([
  66667. BABYLON.serialize()
  66668. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66669. return SSAO2RenderingPipeline;
  66670. }(BABYLON.PostProcessRenderPipeline));
  66671. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66672. })(BABYLON || (BABYLON = {}));
  66673. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66674. // BABYLON.JS Chromatic Aberration GLSL Shader
  66675. // Author: Olivier Guyot
  66676. // Separates very slightly R, G and B colors on the edges of the screen
  66677. // Inspired by Francois Tarlier & Martins Upitis
  66678. var BABYLON;
  66679. (function (BABYLON) {
  66680. var LensRenderingPipeline = /** @class */ (function (_super) {
  66681. __extends(LensRenderingPipeline, _super);
  66682. /**
  66683. * @constructor
  66684. *
  66685. * Effect parameters are as follow:
  66686. * {
  66687. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66688. * edge_blur: number; // from 0 to x (1 for realism)
  66689. * distortion: number; // from 0 to x (1 for realism)
  66690. * grain_amount: number; // from 0 to 1
  66691. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66692. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66693. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66694. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66695. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66696. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66697. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66698. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66699. * }
  66700. * Note: if an effect parameter is unset, effect is disabled
  66701. *
  66702. * @param {string} name - The rendering pipeline name
  66703. * @param {object} parameters - An object containing all parameters (see above)
  66704. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66705. * @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)
  66706. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66707. */
  66708. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66709. if (ratio === void 0) { ratio = 1.0; }
  66710. var _this = _super.call(this, scene.getEngine(), name) || this;
  66711. // Lens effects can be of the following:
  66712. // - chromatic aberration (slight shift of RGB colors)
  66713. // - blur on the edge of the lens
  66714. // - lens distortion
  66715. // - depth-of-field blur & highlights enhancing
  66716. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66717. // - grain effect (noise or custom texture)
  66718. // Two additional texture samplers are needed:
  66719. // - depth map (for depth-of-field)
  66720. // - grain texture
  66721. /**
  66722. * The chromatic aberration PostProcess id in the pipeline
  66723. * @type {string}
  66724. */
  66725. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66726. /**
  66727. * The highlights enhancing PostProcess id in the pipeline
  66728. * @type {string}
  66729. */
  66730. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66731. /**
  66732. * The depth-of-field PostProcess id in the pipeline
  66733. * @type {string}
  66734. */
  66735. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66736. _this._scene = scene;
  66737. // Fetch texture samplers
  66738. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66739. if (parameters.grain_texture) {
  66740. _this._grainTexture = parameters.grain_texture;
  66741. }
  66742. else {
  66743. _this._createGrainTexture();
  66744. }
  66745. // save parameters
  66746. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66747. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66748. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66749. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66750. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66751. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66752. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66753. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66754. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66755. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66756. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66757. // Create effects
  66758. _this._createChromaticAberrationPostProcess(ratio);
  66759. _this._createHighlightsPostProcess(ratio);
  66760. _this._createDepthOfFieldPostProcess(ratio / 4);
  66761. // Set up pipeline
  66762. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66763. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66764. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66765. if (_this._highlightsGain === -1) {
  66766. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66767. }
  66768. // Finish
  66769. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66770. if (cameras) {
  66771. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66772. }
  66773. return _this;
  66774. }
  66775. // public methods (self explanatory)
  66776. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66777. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66778. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66779. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66780. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66781. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66782. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66783. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66784. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66785. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66786. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66787. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66788. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66789. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66790. };
  66791. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66792. this._highlightsPostProcess.updateEffect();
  66793. };
  66794. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66795. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66796. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66797. this._highlightsGain = amount;
  66798. };
  66799. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66800. if (this._highlightsGain === -1) {
  66801. this._highlightsGain = 1.0;
  66802. }
  66803. this._highlightsThreshold = amount;
  66804. };
  66805. LensRenderingPipeline.prototype.disableHighlights = function () {
  66806. this._highlightsGain = -1;
  66807. };
  66808. /**
  66809. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66810. */
  66811. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66812. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66813. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66814. this._chromaticAberrationPostProcess = null;
  66815. this._highlightsPostProcess = null;
  66816. this._depthOfFieldPostProcess = null;
  66817. this._grainTexture.dispose();
  66818. if (disableDepthRender)
  66819. this._scene.disableDepthRenderer();
  66820. };
  66821. // colors shifting and distortion
  66822. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66823. var _this = this;
  66824. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  66825. [], // samplers
  66826. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66827. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66828. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66829. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66830. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66831. effect.setFloat('radialIntensity', 1);
  66832. effect.setFloat2('direction', 17, 17);
  66833. effect.setFloat2('centerPosition', 0.5, 0.5);
  66834. };
  66835. };
  66836. // highlights enhancing
  66837. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66838. var _this = this;
  66839. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66840. [], // samplers
  66841. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66842. this._highlightsPostProcess.onApply = function (effect) {
  66843. effect.setFloat('gain', _this._highlightsGain);
  66844. effect.setFloat('threshold', _this._highlightsThreshold);
  66845. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66846. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66847. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66848. };
  66849. };
  66850. // colors shifting and distortion
  66851. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66852. var _this = this;
  66853. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66854. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66855. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66856. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66857. this._depthOfFieldPostProcess.onApply = function (effect) {
  66858. effect.setTexture("depthSampler", _this._depthTexture);
  66859. effect.setTexture("grainSampler", _this._grainTexture);
  66860. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66861. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66862. effect.setFloat('grain_amount', _this._grainAmount);
  66863. effect.setBool('blur_noise', _this._blurNoise);
  66864. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66865. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66866. effect.setFloat('distortion', _this._distortion);
  66867. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66868. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66869. effect.setFloat('aperture', _this._dofAperture);
  66870. effect.setFloat('darken', _this._dofDarken);
  66871. effect.setFloat('edge_blur', _this._edgeBlur);
  66872. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66873. if (_this._scene.activeCamera) {
  66874. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66875. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66876. }
  66877. };
  66878. };
  66879. // creates a black and white random noise texture, 512x512
  66880. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66881. var size = 512;
  66882. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66883. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66884. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66885. var context = this._grainTexture.getContext();
  66886. var rand = function (min, max) {
  66887. return Math.random() * (max - min) + min;
  66888. };
  66889. var value;
  66890. for (var x = 0; x < size; x++) {
  66891. for (var y = 0; y < size; y++) {
  66892. value = Math.floor(rand(0.42, 0.58) * 255);
  66893. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66894. context.fillRect(x, y, 1, 1);
  66895. }
  66896. }
  66897. this._grainTexture.update(false);
  66898. };
  66899. return LensRenderingPipeline;
  66900. }(BABYLON.PostProcessRenderPipeline));
  66901. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66902. })(BABYLON || (BABYLON = {}));
  66903. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66904. var BABYLON;
  66905. (function (BABYLON) {
  66906. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66907. __extends(StandardRenderingPipeline, _super);
  66908. /**
  66909. * @constructor
  66910. * @param {string} name - The rendering pipeline name
  66911. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66912. * @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)
  66913. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66914. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66915. */
  66916. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66917. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66918. var _this = _super.call(this, scene.getEngine(), name) || this;
  66919. _this.downSampleX4PostProcess = null;
  66920. _this.brightPassPostProcess = null;
  66921. _this.blurHPostProcesses = [];
  66922. _this.blurVPostProcesses = [];
  66923. _this.textureAdderPostProcess = null;
  66924. _this.volumetricLightPostProcess = null;
  66925. _this.volumetricLightSmoothXPostProcess = null;
  66926. _this.volumetricLightSmoothYPostProcess = null;
  66927. _this.volumetricLightMergePostProces = null;
  66928. _this.volumetricLightFinalPostProcess = null;
  66929. _this.luminancePostProcess = null;
  66930. _this.luminanceDownSamplePostProcesses = [];
  66931. _this.hdrPostProcess = null;
  66932. _this.textureAdderFinalPostProcess = null;
  66933. _this.lensFlareFinalPostProcess = null;
  66934. _this.hdrFinalPostProcess = null;
  66935. _this.lensFlarePostProcess = null;
  66936. _this.lensFlareComposePostProcess = null;
  66937. _this.motionBlurPostProcess = null;
  66938. _this.depthOfFieldPostProcess = null;
  66939. // Values
  66940. _this.brightThreshold = 1.0;
  66941. _this.blurWidth = 512.0;
  66942. _this.horizontalBlur = false;
  66943. _this.exposure = 1.0;
  66944. _this.lensTexture = null;
  66945. _this.volumetricLightCoefficient = 0.2;
  66946. _this.volumetricLightPower = 4.0;
  66947. _this.volumetricLightBlurScale = 64.0;
  66948. _this.sourceLight = null;
  66949. _this.hdrMinimumLuminance = 1.0;
  66950. _this.hdrDecreaseRate = 0.5;
  66951. _this.hdrIncreaseRate = 0.5;
  66952. _this.lensColorTexture = null;
  66953. _this.lensFlareStrength = 20.0;
  66954. _this.lensFlareGhostDispersal = 1.4;
  66955. _this.lensFlareHaloWidth = 0.7;
  66956. _this.lensFlareDistortionStrength = 16.0;
  66957. _this.lensStarTexture = null;
  66958. _this.lensFlareDirtTexture = null;
  66959. _this.depthOfFieldDistance = 10.0;
  66960. _this.depthOfFieldBlurWidth = 64.0;
  66961. _this.motionStrength = 1.0;
  66962. // IAnimatable
  66963. _this.animations = [];
  66964. _this._currentDepthOfFieldSource = null;
  66965. _this._hdrCurrentLuminance = 1.0;
  66966. // Getters and setters
  66967. _this._bloomEnabled = true;
  66968. _this._depthOfFieldEnabled = false;
  66969. _this._vlsEnabled = false;
  66970. _this._lensFlareEnabled = false;
  66971. _this._hdrEnabled = false;
  66972. _this._motionBlurEnabled = false;
  66973. _this._motionBlurSamples = 64.0;
  66974. _this._volumetricLightStepsCount = 50.0;
  66975. _this._cameras = cameras || [];
  66976. // Initialize
  66977. _this._scene = scene;
  66978. _this._basePostProcess = originalPostProcess;
  66979. _this._ratio = ratio;
  66980. // Misc
  66981. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66982. // Finish
  66983. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66984. _this._buildPipeline();
  66985. return _this;
  66986. }
  66987. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66988. get: function () {
  66989. return this._bloomEnabled;
  66990. },
  66991. set: function (enabled) {
  66992. if (this._bloomEnabled === enabled) {
  66993. return;
  66994. }
  66995. this._bloomEnabled = enabled;
  66996. this._buildPipeline();
  66997. },
  66998. enumerable: true,
  66999. configurable: true
  67000. });
  67001. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67002. get: function () {
  67003. return this._depthOfFieldEnabled;
  67004. },
  67005. set: function (enabled) {
  67006. if (this._depthOfFieldEnabled === enabled) {
  67007. return;
  67008. }
  67009. this._depthOfFieldEnabled = enabled;
  67010. this._buildPipeline();
  67011. },
  67012. enumerable: true,
  67013. configurable: true
  67014. });
  67015. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67016. get: function () {
  67017. return this._lensFlareEnabled;
  67018. },
  67019. set: function (enabled) {
  67020. if (this._lensFlareEnabled === enabled) {
  67021. return;
  67022. }
  67023. this._lensFlareEnabled = enabled;
  67024. this._buildPipeline();
  67025. },
  67026. enumerable: true,
  67027. configurable: true
  67028. });
  67029. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67030. get: function () {
  67031. return this._hdrEnabled;
  67032. },
  67033. set: function (enabled) {
  67034. if (this._hdrEnabled === enabled) {
  67035. return;
  67036. }
  67037. this._hdrEnabled = enabled;
  67038. this._buildPipeline();
  67039. },
  67040. enumerable: true,
  67041. configurable: true
  67042. });
  67043. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67044. get: function () {
  67045. return this._vlsEnabled;
  67046. },
  67047. set: function (enabled) {
  67048. if (this._vlsEnabled === enabled) {
  67049. return;
  67050. }
  67051. if (enabled) {
  67052. var geometry = this._scene.enableGeometryBufferRenderer();
  67053. if (!geometry) {
  67054. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67055. return;
  67056. }
  67057. }
  67058. this._vlsEnabled = enabled;
  67059. this._buildPipeline();
  67060. },
  67061. enumerable: true,
  67062. configurable: true
  67063. });
  67064. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67065. get: function () {
  67066. return this._motionBlurEnabled;
  67067. },
  67068. set: function (enabled) {
  67069. if (this._motionBlurEnabled === enabled) {
  67070. return;
  67071. }
  67072. this._motionBlurEnabled = enabled;
  67073. this._buildPipeline();
  67074. },
  67075. enumerable: true,
  67076. configurable: true
  67077. });
  67078. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67079. get: function () {
  67080. return this._volumetricLightStepsCount;
  67081. },
  67082. set: function (count) {
  67083. if (this.volumetricLightPostProcess) {
  67084. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67085. }
  67086. this._volumetricLightStepsCount = count;
  67087. },
  67088. enumerable: true,
  67089. configurable: true
  67090. });
  67091. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67092. get: function () {
  67093. return this._motionBlurSamples;
  67094. },
  67095. set: function (samples) {
  67096. if (this.motionBlurPostProcess) {
  67097. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67098. }
  67099. this._motionBlurSamples = samples;
  67100. },
  67101. enumerable: true,
  67102. configurable: true
  67103. });
  67104. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67105. var _this = this;
  67106. var ratio = this._ratio;
  67107. var scene = this._scene;
  67108. this._disposePostProcesses();
  67109. this._reset();
  67110. // Create pass post-process
  67111. if (!this._basePostProcess) {
  67112. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67113. this.originalPostProcess.onApply = function (effect) {
  67114. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67115. };
  67116. }
  67117. else {
  67118. this.originalPostProcess = this._basePostProcess;
  67119. }
  67120. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67121. this._currentDepthOfFieldSource = this.originalPostProcess;
  67122. if (this._vlsEnabled) {
  67123. // Create volumetric light
  67124. this._createVolumetricLightPostProcess(scene, ratio);
  67125. // Create volumetric light final post-process
  67126. 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);
  67127. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67128. }
  67129. if (this._bloomEnabled) {
  67130. // Create down sample X4 post-process
  67131. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67132. // Create bright pass post-process
  67133. this._createBrightPassPostProcess(scene, ratio / 2);
  67134. // Create gaussian blur post-processes (down sampling blurs)
  67135. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67136. // Create texture adder post-process
  67137. this._createTextureAdderPostProcess(scene, ratio);
  67138. // Create depth-of-field source post-process
  67139. 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);
  67140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67141. }
  67142. if (this._lensFlareEnabled) {
  67143. // Create lens flare post-process
  67144. this._createLensFlarePostProcess(scene, ratio);
  67145. // Create depth-of-field source post-process post lens-flare and disable it now
  67146. 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);
  67147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67148. }
  67149. if (this._hdrEnabled) {
  67150. // Create luminance
  67151. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67152. // Create HDR
  67153. this._createHdrPostProcess(scene, ratio);
  67154. // Create depth-of-field source post-process post hdr and disable it now
  67155. 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);
  67156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67157. }
  67158. if (this._depthOfFieldEnabled) {
  67159. // Create gaussian blur used by depth-of-field
  67160. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67161. // Create depth-of-field post-process
  67162. this._createDepthOfFieldPostProcess(scene, ratio);
  67163. }
  67164. if (this._motionBlurEnabled) {
  67165. // Create motion blur post-process
  67166. this._createMotionBlurPostProcess(scene, ratio);
  67167. }
  67168. if (this._cameras !== null) {
  67169. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67170. }
  67171. };
  67172. // Down Sample X4 Post-Processs
  67173. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67174. var _this = this;
  67175. var downSampleX4Offsets = new Array(32);
  67176. 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);
  67177. this.downSampleX4PostProcess.onApply = function (effect) {
  67178. var id = 0;
  67179. var width = _this.downSampleX4PostProcess.width;
  67180. var height = _this.downSampleX4PostProcess.height;
  67181. for (var i = -2; i < 2; i++) {
  67182. for (var j = -2; j < 2; j++) {
  67183. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67184. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67185. id += 2;
  67186. }
  67187. }
  67188. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67189. };
  67190. // Add to pipeline
  67191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67192. };
  67193. // Brightpass Post-Process
  67194. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67195. var _this = this;
  67196. var brightOffsets = new Array(8);
  67197. 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);
  67198. this.brightPassPostProcess.onApply = function (effect) {
  67199. var sU = (1.0 / _this.brightPassPostProcess.width);
  67200. var sV = (1.0 / _this.brightPassPostProcess.height);
  67201. brightOffsets[0] = -0.5 * sU;
  67202. brightOffsets[1] = 0.5 * sV;
  67203. brightOffsets[2] = 0.5 * sU;
  67204. brightOffsets[3] = 0.5 * sV;
  67205. brightOffsets[4] = -0.5 * sU;
  67206. brightOffsets[5] = -0.5 * sV;
  67207. brightOffsets[6] = 0.5 * sU;
  67208. brightOffsets[7] = -0.5 * sV;
  67209. effect.setArray2("dsOffsets", brightOffsets);
  67210. effect.setFloat("brightThreshold", _this.brightThreshold);
  67211. };
  67212. // Add to pipeline
  67213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67214. };
  67215. // Create blur H&V post-processes
  67216. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67217. var _this = this;
  67218. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67219. var engine = scene.getEngine();
  67220. 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);
  67221. 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);
  67222. blurX.onActivateObservable.add(function () {
  67223. var dw = blurX.width / engine.getRenderWidth();
  67224. blurX.kernel = _this[blurWidthKey] * dw;
  67225. });
  67226. blurY.onActivateObservable.add(function () {
  67227. var dw = blurY.height / engine.getRenderHeight();
  67228. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67229. });
  67230. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67232. this.blurHPostProcesses.push(blurX);
  67233. this.blurVPostProcesses.push(blurY);
  67234. };
  67235. // Create texture adder post-process
  67236. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67237. var _this = this;
  67238. 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);
  67239. this.textureAdderPostProcess.onApply = function (effect) {
  67240. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67241. effect.setTexture("lensSampler", _this.lensTexture);
  67242. effect.setFloat("exposure", _this.exposure);
  67243. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67244. };
  67245. // Add to pipeline
  67246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67247. };
  67248. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67249. var _this = this;
  67250. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67251. geometryRenderer.enablePosition = true;
  67252. var geometry = geometryRenderer.getGBuffer();
  67253. // Base post-process
  67254. 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));
  67255. var depthValues = BABYLON.Vector2.Zero();
  67256. this.volumetricLightPostProcess.onApply = function (effect) {
  67257. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67258. var generator = _this.sourceLight.getShadowGenerator();
  67259. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67260. effect.setTexture("positionSampler", geometry.textures[2]);
  67261. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67262. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67263. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67264. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67265. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67266. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67267. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67268. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67269. effect.setVector2("depthValues", depthValues);
  67270. }
  67271. };
  67272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67273. // Smooth
  67274. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67275. // Merge
  67276. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67277. this.volumetricLightMergePostProces.onApply = function (effect) {
  67278. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67279. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67280. };
  67281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67282. };
  67283. // Create luminance
  67284. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67285. var _this = this;
  67286. // Create luminance
  67287. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67288. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67289. var offsets = [];
  67290. this.luminancePostProcess.onApply = function (effect) {
  67291. var sU = (1.0 / _this.luminancePostProcess.width);
  67292. var sV = (1.0 / _this.luminancePostProcess.height);
  67293. offsets[0] = -0.5 * sU;
  67294. offsets[1] = 0.5 * sV;
  67295. offsets[2] = 0.5 * sU;
  67296. offsets[3] = 0.5 * sV;
  67297. offsets[4] = -0.5 * sU;
  67298. offsets[5] = -0.5 * sV;
  67299. offsets[6] = 0.5 * sU;
  67300. offsets[7] = -0.5 * sV;
  67301. effect.setArray2("lumOffsets", offsets);
  67302. };
  67303. // Add to pipeline
  67304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67305. // Create down sample luminance
  67306. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67307. var size = Math.pow(3, i);
  67308. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67309. if (i === 0) {
  67310. defines += "#define FINAL_DOWN_SAMPLER";
  67311. }
  67312. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67313. this.luminanceDownSamplePostProcesses.push(postProcess);
  67314. }
  67315. // Create callbacks and add effects
  67316. var lastLuminance = this.luminancePostProcess;
  67317. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67318. var downSampleOffsets = new Array(18);
  67319. pp.onApply = function (effect) {
  67320. if (!lastLuminance) {
  67321. return;
  67322. }
  67323. var id = 0;
  67324. for (var x = -1; x < 2; x++) {
  67325. for (var y = -1; y < 2; y++) {
  67326. downSampleOffsets[id] = x / lastLuminance.width;
  67327. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67328. id += 2;
  67329. }
  67330. }
  67331. effect.setArray2("dsOffsets", downSampleOffsets);
  67332. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67333. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67334. lastLuminance = _this.luminancePostProcess;
  67335. }
  67336. else {
  67337. lastLuminance = pp;
  67338. }
  67339. };
  67340. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67341. pp.onAfterRender = function (effect) {
  67342. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67343. 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);
  67344. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67345. };
  67346. }
  67347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67348. });
  67349. };
  67350. // Create HDR post-process
  67351. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67352. var _this = this;
  67353. 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);
  67354. var outputLiminance = 1;
  67355. var time = 0;
  67356. var lastTime = 0;
  67357. this.hdrPostProcess.onApply = function (effect) {
  67358. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67359. time += scene.getEngine().getDeltaTime();
  67360. if (outputLiminance < 0) {
  67361. outputLiminance = _this._hdrCurrentLuminance;
  67362. }
  67363. else {
  67364. var dt = (lastTime - time) / 1000.0;
  67365. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67366. outputLiminance += _this.hdrDecreaseRate * dt;
  67367. }
  67368. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67369. outputLiminance -= _this.hdrIncreaseRate * dt;
  67370. }
  67371. else {
  67372. outputLiminance = _this._hdrCurrentLuminance;
  67373. }
  67374. }
  67375. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67376. effect.setFloat("averageLuminance", outputLiminance);
  67377. lastTime = time;
  67378. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67379. };
  67380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67381. };
  67382. // Create lens flare post-process
  67383. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67384. var _this = this;
  67385. 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);
  67386. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67387. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67388. 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);
  67389. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67390. var resolution = new BABYLON.Vector2(0, 0);
  67391. // Lens flare
  67392. this.lensFlarePostProcess.onApply = function (effect) {
  67393. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67394. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67395. effect.setFloat("strength", _this.lensFlareStrength);
  67396. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67397. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67398. // Shift
  67399. resolution.x = _this.lensFlarePostProcess.width;
  67400. resolution.y = _this.lensFlarePostProcess.height;
  67401. effect.setVector2("resolution", resolution);
  67402. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67403. };
  67404. // Compose
  67405. 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);
  67406. 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);
  67407. this.lensFlareComposePostProcess.onApply = function (effect) {
  67408. if (!_this._scene.activeCamera) {
  67409. return;
  67410. }
  67411. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67412. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67413. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67414. // Lens start rotation matrix
  67415. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67416. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67417. 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));
  67418. camRot *= 4.0;
  67419. 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);
  67420. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67421. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67422. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67423. };
  67424. };
  67425. // Create depth-of-field post-process
  67426. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67427. var _this = this;
  67428. 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);
  67429. this.depthOfFieldPostProcess.onApply = function (effect) {
  67430. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67431. effect.setTexture("depthSampler", _this._getDepthTexture());
  67432. effect.setFloat("distance", _this.depthOfFieldDistance);
  67433. };
  67434. // Add to pipeline
  67435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67436. };
  67437. // Create motion blur post-process
  67438. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67439. var _this = this;
  67440. 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);
  67441. var motionScale = 0;
  67442. var prevViewProjection = BABYLON.Matrix.Identity();
  67443. var invViewProjection = BABYLON.Matrix.Identity();
  67444. var viewProjection = BABYLON.Matrix.Identity();
  67445. var screenSize = BABYLON.Vector2.Zero();
  67446. this.motionBlurPostProcess.onApply = function (effect) {
  67447. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67448. viewProjection.invertToRef(invViewProjection);
  67449. effect.setMatrix("inverseViewProjection", invViewProjection);
  67450. effect.setMatrix("prevViewProjection", prevViewProjection);
  67451. prevViewProjection = viewProjection;
  67452. screenSize.x = _this.motionBlurPostProcess.width;
  67453. screenSize.y = _this.motionBlurPostProcess.height;
  67454. effect.setVector2("screenSize", screenSize);
  67455. motionScale = scene.getEngine().getFps() / 60.0;
  67456. effect.setFloat("motionScale", motionScale);
  67457. effect.setFloat("motionStrength", _this.motionStrength);
  67458. effect.setTexture("depthSampler", _this._getDepthTexture());
  67459. };
  67460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67461. };
  67462. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67463. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67464. var renderer = this._scene.enableGeometryBufferRenderer();
  67465. return renderer.getGBuffer().textures[0];
  67466. }
  67467. return this._scene.enableDepthRenderer().getDepthMap();
  67468. };
  67469. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67470. for (var i = 0; i < this._cameras.length; i++) {
  67471. var camera = this._cameras[i];
  67472. if (this.originalPostProcess) {
  67473. this.originalPostProcess.dispose(camera);
  67474. }
  67475. if (this.downSampleX4PostProcess) {
  67476. this.downSampleX4PostProcess.dispose(camera);
  67477. }
  67478. if (this.brightPassPostProcess) {
  67479. this.brightPassPostProcess.dispose(camera);
  67480. }
  67481. if (this.textureAdderPostProcess) {
  67482. this.textureAdderPostProcess.dispose(camera);
  67483. }
  67484. if (this.textureAdderFinalPostProcess) {
  67485. this.textureAdderFinalPostProcess.dispose(camera);
  67486. }
  67487. if (this.volumetricLightPostProcess) {
  67488. this.volumetricLightPostProcess.dispose(camera);
  67489. }
  67490. if (this.volumetricLightSmoothXPostProcess) {
  67491. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67492. }
  67493. if (this.volumetricLightSmoothYPostProcess) {
  67494. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67495. }
  67496. if (this.volumetricLightMergePostProces) {
  67497. this.volumetricLightMergePostProces.dispose(camera);
  67498. }
  67499. if (this.volumetricLightFinalPostProcess) {
  67500. this.volumetricLightFinalPostProcess.dispose(camera);
  67501. }
  67502. if (this.lensFlarePostProcess) {
  67503. this.lensFlarePostProcess.dispose(camera);
  67504. }
  67505. if (this.lensFlareComposePostProcess) {
  67506. this.lensFlareComposePostProcess.dispose(camera);
  67507. }
  67508. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67509. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67510. }
  67511. if (this.luminancePostProcess) {
  67512. this.luminancePostProcess.dispose(camera);
  67513. }
  67514. if (this.hdrPostProcess) {
  67515. this.hdrPostProcess.dispose(camera);
  67516. }
  67517. if (this.hdrFinalPostProcess) {
  67518. this.hdrFinalPostProcess.dispose(camera);
  67519. }
  67520. if (this.depthOfFieldPostProcess) {
  67521. this.depthOfFieldPostProcess.dispose(camera);
  67522. }
  67523. if (this.motionBlurPostProcess) {
  67524. this.motionBlurPostProcess.dispose(camera);
  67525. }
  67526. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67527. this.blurHPostProcesses[j].dispose(camera);
  67528. }
  67529. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67530. this.blurVPostProcesses[j].dispose(camera);
  67531. }
  67532. }
  67533. this.originalPostProcess = null;
  67534. this.downSampleX4PostProcess = null;
  67535. this.brightPassPostProcess = null;
  67536. this.textureAdderPostProcess = null;
  67537. this.textureAdderFinalPostProcess = null;
  67538. this.volumetricLightPostProcess = null;
  67539. this.volumetricLightSmoothXPostProcess = null;
  67540. this.volumetricLightSmoothYPostProcess = null;
  67541. this.volumetricLightMergePostProces = null;
  67542. this.volumetricLightFinalPostProcess = null;
  67543. this.lensFlarePostProcess = null;
  67544. this.lensFlareComposePostProcess = null;
  67545. this.luminancePostProcess = null;
  67546. this.hdrPostProcess = null;
  67547. this.hdrFinalPostProcess = null;
  67548. this.depthOfFieldPostProcess = null;
  67549. this.motionBlurPostProcess = null;
  67550. this.luminanceDownSamplePostProcesses = [];
  67551. this.blurHPostProcesses = [];
  67552. this.blurVPostProcesses = [];
  67553. };
  67554. // Dispose
  67555. StandardRenderingPipeline.prototype.dispose = function () {
  67556. this._disposePostProcesses();
  67557. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67558. _super.prototype.dispose.call(this);
  67559. };
  67560. // Serialize rendering pipeline
  67561. StandardRenderingPipeline.prototype.serialize = function () {
  67562. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67563. serializationObject.customType = "StandardRenderingPipeline";
  67564. return serializationObject;
  67565. };
  67566. /**
  67567. * Static members
  67568. */
  67569. // Parse serialized pipeline
  67570. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67571. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67572. };
  67573. // Luminance steps
  67574. StandardRenderingPipeline.LuminanceSteps = 6;
  67575. __decorate([
  67576. BABYLON.serialize()
  67577. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67578. __decorate([
  67579. BABYLON.serialize()
  67580. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67581. __decorate([
  67582. BABYLON.serialize()
  67583. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67584. __decorate([
  67585. BABYLON.serialize()
  67586. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67587. __decorate([
  67588. BABYLON.serializeAsTexture("lensTexture")
  67589. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67590. __decorate([
  67591. BABYLON.serialize()
  67592. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67593. __decorate([
  67594. BABYLON.serialize()
  67595. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67596. __decorate([
  67597. BABYLON.serialize()
  67598. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67599. __decorate([
  67600. BABYLON.serialize()
  67601. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67602. __decorate([
  67603. BABYLON.serialize()
  67604. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67605. __decorate([
  67606. BABYLON.serialize()
  67607. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67608. __decorate([
  67609. BABYLON.serializeAsTexture("lensColorTexture")
  67610. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67611. __decorate([
  67612. BABYLON.serialize()
  67613. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67614. __decorate([
  67615. BABYLON.serialize()
  67616. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67617. __decorate([
  67618. BABYLON.serialize()
  67619. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67620. __decorate([
  67621. BABYLON.serialize()
  67622. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67623. __decorate([
  67624. BABYLON.serializeAsTexture("lensStarTexture")
  67625. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67626. __decorate([
  67627. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67628. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67629. __decorate([
  67630. BABYLON.serialize()
  67631. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67632. __decorate([
  67633. BABYLON.serialize()
  67634. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67635. __decorate([
  67636. BABYLON.serialize()
  67637. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67638. __decorate([
  67639. BABYLON.serialize()
  67640. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67641. __decorate([
  67642. BABYLON.serialize()
  67643. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67644. __decorate([
  67645. BABYLON.serialize()
  67646. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67647. __decorate([
  67648. BABYLON.serialize()
  67649. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67650. __decorate([
  67651. BABYLON.serialize()
  67652. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67653. __decorate([
  67654. BABYLON.serialize()
  67655. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67656. __decorate([
  67657. BABYLON.serialize()
  67658. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67659. __decorate([
  67660. BABYLON.serialize()
  67661. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67662. __decorate([
  67663. BABYLON.serialize()
  67664. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67665. return StandardRenderingPipeline;
  67666. }(BABYLON.PostProcessRenderPipeline));
  67667. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67668. })(BABYLON || (BABYLON = {}));
  67669. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67670. var BABYLON;
  67671. (function (BABYLON) {
  67672. var FxaaPostProcess = /** @class */ (function (_super) {
  67673. __extends(FxaaPostProcess, _super);
  67674. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67675. if (camera === void 0) { camera = null; }
  67676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67677. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67678. _this.onApplyObservable.add(function (effect) {
  67679. var texelSize = _this.texelSize;
  67680. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67681. });
  67682. return _this;
  67683. }
  67684. return FxaaPostProcess;
  67685. }(BABYLON.PostProcess));
  67686. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67687. })(BABYLON || (BABYLON = {}));
  67688. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67689. var BABYLON;
  67690. (function (BABYLON) {
  67691. /**
  67692. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67693. */
  67694. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67695. __extends(CircleOfConfusionPostProcess, _super);
  67696. /**
  67697. * Creates a new instance of @see CircleOfConfusionPostProcess
  67698. * @param name The name of the effect.
  67699. * @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.
  67700. * @param options The required width/height ratio to downsize to before computing the render pass.
  67701. * @param camera The camera to apply the render pass to.
  67702. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67703. * @param engine The engine which the post process will be applied. (default: current engine)
  67704. * @param reusable If the post process can be reused on the same frame. (default: false)
  67705. * @param textureType Type of textures used when performing the post process. (default: 0)
  67706. */
  67707. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67708. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67709. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67710. /**
  67711. * 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.
  67712. */
  67713. _this.lensSize = 50;
  67714. /**
  67715. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67716. */
  67717. _this.fStop = 1.4;
  67718. /**
  67719. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67720. */
  67721. _this.focusDistance = 2000;
  67722. /**
  67723. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67724. */
  67725. _this.focalLength = 50;
  67726. _this._depthTexture = null;
  67727. _this._depthTexture = depthTexture;
  67728. _this.onApplyObservable.add(function (effect) {
  67729. if (!_this._depthTexture) {
  67730. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  67731. return;
  67732. }
  67733. effect.setTexture("depthSampler", _this._depthTexture);
  67734. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67735. var aperture = _this.lensSize / _this.fStop;
  67736. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67737. effect.setFloat('focusDistance', _this.focusDistance);
  67738. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67739. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  67740. });
  67741. return _this;
  67742. }
  67743. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  67744. /**
  67745. * 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.
  67746. */
  67747. set: function (value) {
  67748. this._depthTexture = value;
  67749. },
  67750. enumerable: true,
  67751. configurable: true
  67752. });
  67753. return CircleOfConfusionPostProcess;
  67754. }(BABYLON.PostProcess));
  67755. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67756. })(BABYLON || (BABYLON = {}));
  67757. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67758. var BABYLON;
  67759. (function (BABYLON) {
  67760. /**
  67761. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67762. */
  67763. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67764. __extends(DepthOfFieldMergePostProcess, _super);
  67765. /**
  67766. * Creates a new instance of @see CircleOfConfusionPostProcess
  67767. * @param name The name of the effect.
  67768. * @param original The non-blurred image to be modified
  67769. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67770. * @param blurSteps Incrimental bluring post processes.
  67771. * @param options The required width/height ratio to downsize to before computing the render pass.
  67772. * @param camera The camera to apply the render pass to.
  67773. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67774. * @param engine The engine which the post process will be applied. (default: current engine)
  67775. * @param reusable If the post process can be reused on the same frame. (default: false)
  67776. * @param textureType Type of textures used when performing the post process. (default: 0)
  67777. */
  67778. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67779. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67780. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67781. _this.onApplyObservable.add(function (effect) {
  67782. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67783. effect.setTextureFromPostProcess("originalSampler", original);
  67784. blurSteps.forEach(function (step, index) {
  67785. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67786. });
  67787. });
  67788. return _this;
  67789. }
  67790. return DepthOfFieldMergePostProcess;
  67791. }(BABYLON.PostProcess));
  67792. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67793. })(BABYLON || (BABYLON = {}));
  67794. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67795. var BABYLON;
  67796. (function (BABYLON) {
  67797. /**
  67798. * Specifies the level of max blur that should be applied when using the depth of field effect
  67799. */
  67800. var DepthOfFieldEffectBlurLevel;
  67801. (function (DepthOfFieldEffectBlurLevel) {
  67802. /**
  67803. * Subtle blur
  67804. */
  67805. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67806. /**
  67807. * Medium blur
  67808. */
  67809. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67810. /**
  67811. * Large blur
  67812. */
  67813. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67814. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67815. ;
  67816. /**
  67817. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67818. */
  67819. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67820. __extends(DepthOfFieldEffect, _super);
  67821. /**
  67822. * Creates a new instance of @see DepthOfFieldEffect
  67823. * @param scene The scene the effect belongs to.
  67824. * @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.
  67825. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67826. */
  67827. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  67828. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67829. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67830. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67831. return _this._effects;
  67832. }, true) || this;
  67833. _this._effects = [];
  67834. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67835. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67836. // Capture circle of confusion texture
  67837. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67838. _this._depthOfFieldPass.autoClear = false;
  67839. // 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)
  67840. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67841. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67842. _this._depthOfFieldBlurY = [];
  67843. _this._depthOfFieldBlurX = [];
  67844. var blurCount = 1;
  67845. var kernelSize = 15;
  67846. switch (blurLevel) {
  67847. case DepthOfFieldEffectBlurLevel.High: {
  67848. blurCount = 3;
  67849. kernelSize = 51;
  67850. break;
  67851. }
  67852. case DepthOfFieldEffectBlurLevel.Medium: {
  67853. blurCount = 2;
  67854. kernelSize = 31;
  67855. break;
  67856. }
  67857. default: {
  67858. kernelSize = 15;
  67859. blurCount = 1;
  67860. break;
  67861. }
  67862. }
  67863. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67864. for (var i = 0; i < blurCount; i++) {
  67865. 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);
  67866. blurY.autoClear = false;
  67867. 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);
  67868. blurX.autoClear = false;
  67869. _this._depthOfFieldBlurY.push(blurY);
  67870. _this._depthOfFieldBlurX.push(blurX);
  67871. }
  67872. // Merge blurred images with original image based on circleOfConfusion
  67873. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67874. _this._depthOfFieldMerge.autoClear = false;
  67875. // Set all post processes on the effect.
  67876. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67877. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67878. _this._effects.push(_this._depthOfFieldBlurY[i]);
  67879. _this._effects.push(_this._depthOfFieldBlurX[i]);
  67880. }
  67881. _this._effects.push(_this._depthOfFieldMerge);
  67882. return _this;
  67883. }
  67884. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67885. get: function () {
  67886. return this._circleOfConfusion.focalLength;
  67887. },
  67888. /**
  67889. * The focal the length of the camera used in the effect
  67890. */
  67891. set: function (value) {
  67892. this._circleOfConfusion.focalLength = value;
  67893. },
  67894. enumerable: true,
  67895. configurable: true
  67896. });
  67897. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67898. get: function () {
  67899. return this._circleOfConfusion.fStop;
  67900. },
  67901. /**
  67902. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67903. */
  67904. set: function (value) {
  67905. this._circleOfConfusion.fStop = value;
  67906. },
  67907. enumerable: true,
  67908. configurable: true
  67909. });
  67910. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67911. get: function () {
  67912. return this._circleOfConfusion.focusDistance;
  67913. },
  67914. /**
  67915. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67916. */
  67917. set: function (value) {
  67918. this._circleOfConfusion.focusDistance = value;
  67919. },
  67920. enumerable: true,
  67921. configurable: true
  67922. });
  67923. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67924. get: function () {
  67925. return this._circleOfConfusion.lensSize;
  67926. },
  67927. /**
  67928. * 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.
  67929. */
  67930. set: function (value) {
  67931. this._circleOfConfusion.lensSize = value;
  67932. },
  67933. enumerable: true,
  67934. configurable: true
  67935. });
  67936. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  67937. /**
  67938. * 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.
  67939. */
  67940. set: function (value) {
  67941. this._circleOfConfusion.depthTexture = value;
  67942. },
  67943. enumerable: true,
  67944. configurable: true
  67945. });
  67946. /**
  67947. * Disposes each of the internal effects for a given camera.
  67948. * @param camera The camera to dispose the effect on.
  67949. */
  67950. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67951. this._depthOfFieldPass.dispose(camera);
  67952. this._circleOfConfusion.dispose(camera);
  67953. this._depthOfFieldBlurX.forEach(function (element) {
  67954. element.dispose(camera);
  67955. });
  67956. this._depthOfFieldBlurY.forEach(function (element) {
  67957. element.dispose(camera);
  67958. });
  67959. this._depthOfFieldMerge.dispose(camera);
  67960. };
  67961. return DepthOfFieldEffect;
  67962. }(BABYLON.PostProcessRenderEffect));
  67963. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67964. })(BABYLON || (BABYLON = {}));
  67965. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67966. var BABYLON;
  67967. (function (BABYLON) {
  67968. /**
  67969. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67970. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67971. */
  67972. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67973. __extends(DefaultRenderingPipeline, _super);
  67974. /**
  67975. * @constructor
  67976. * @param {string} name - The rendering pipeline name
  67977. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67978. * @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)
  67979. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67980. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67981. */
  67982. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67983. if (automaticBuild === void 0) { automaticBuild = true; }
  67984. var _this = _super.call(this, scene.getEngine(), name) || this;
  67985. _this._originalCameras = [];
  67986. /**
  67987. * ID of the sharpen post process,
  67988. */
  67989. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  67990. /**
  67991. * ID of the pass post process used for bloom,
  67992. */
  67993. _this.PassPostProcessId = "PassPostProcessEffect";
  67994. /**
  67995. * ID of the highlight post process used for bloom,
  67996. */
  67997. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67998. /**
  67999. * ID of the blurX post process used for bloom,
  68000. */
  68001. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68002. /**
  68003. * ID of the blurY post process used for bloom,
  68004. */
  68005. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68006. /**
  68007. * ID of the copy back post process used for bloom,
  68008. */
  68009. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68010. /**
  68011. * ID of the image processing post process;
  68012. */
  68013. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68014. /**
  68015. * ID of the Fast Approximate Anti-Aliasing post process;
  68016. */
  68017. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68018. /**
  68019. * ID of the final merge post process;
  68020. */
  68021. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68022. /**
  68023. * ID of the chromatic aberration post process,
  68024. */
  68025. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  68026. /**
  68027. * Animations which can be used to tweak settings over a period of time
  68028. */
  68029. _this.animations = [];
  68030. // Values
  68031. _this._sharpenEnabled = false;
  68032. _this._bloomEnabled = false;
  68033. _this._depthOfFieldEnabled = false;
  68034. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68035. _this._fxaaEnabled = false;
  68036. _this._msaaEnabled = false;
  68037. _this._imageProcessingEnabled = true;
  68038. _this._bloomScale = 0.6;
  68039. _this._chromaticAberrationEnabled = false;
  68040. _this._buildAllowed = true;
  68041. /**
  68042. * Specifies the size of the bloom blur kernel, relative to the final output size
  68043. */
  68044. _this.bloomKernel = 64;
  68045. /**
  68046. * Specifies the weight of the bloom in the final rendering
  68047. */
  68048. _this._bloomWeight = 0.15;
  68049. _this._prevPostProcess = null;
  68050. _this._prevPrevPostProcess = null;
  68051. _this._cameras = cameras || [];
  68052. _this._originalCameras = _this._cameras.slice();
  68053. _this._buildAllowed = automaticBuild;
  68054. // Initialize
  68055. _this._scene = scene;
  68056. var caps = _this._scene.getEngine().getCaps();
  68057. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68058. // Misc
  68059. if (_this._hdr) {
  68060. if (caps.textureHalfFloatRender) {
  68061. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68062. }
  68063. else if (caps.textureFloatRender) {
  68064. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68065. }
  68066. }
  68067. else {
  68068. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68069. }
  68070. // Attach
  68071. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68072. var engine = _this._scene.getEngine();
  68073. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType);
  68074. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  68075. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType);
  68076. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType);
  68077. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  68078. _this._buildPipeline();
  68079. return _this;
  68080. }
  68081. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  68082. get: function () {
  68083. return this._sharpenEnabled;
  68084. },
  68085. /**
  68086. * Enable or disable the sharpen process from the pipeline
  68087. */
  68088. set: function (enabled) {
  68089. if (this._sharpenEnabled === enabled) {
  68090. return;
  68091. }
  68092. this._sharpenEnabled = enabled;
  68093. this._buildPipeline();
  68094. },
  68095. enumerable: true,
  68096. configurable: true
  68097. });
  68098. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68099. get: function () {
  68100. return this._bloomWeight;
  68101. },
  68102. /**
  68103. * The strength of the bloom.
  68104. */
  68105. set: function (value) {
  68106. if (this._bloomWeight === value) {
  68107. return;
  68108. }
  68109. this._bloomWeight = value;
  68110. if (this._hdr && this.copyBack) {
  68111. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68112. }
  68113. },
  68114. enumerable: true,
  68115. configurable: true
  68116. });
  68117. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68118. get: function () {
  68119. return this._bloomScale;
  68120. },
  68121. /**
  68122. * The scale of the bloom, lower value will provide better performance.
  68123. */
  68124. set: function (value) {
  68125. if (this._bloomScale === value) {
  68126. return;
  68127. }
  68128. this._bloomScale = value;
  68129. this._buildPipeline();
  68130. },
  68131. enumerable: true,
  68132. configurable: true
  68133. });
  68134. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68135. get: function () {
  68136. return this._bloomEnabled;
  68137. },
  68138. /**
  68139. * Enable or disable the bloom from the pipeline
  68140. */
  68141. set: function (enabled) {
  68142. if (this._bloomEnabled === enabled) {
  68143. return;
  68144. }
  68145. this._bloomEnabled = enabled;
  68146. this._buildPipeline();
  68147. },
  68148. enumerable: true,
  68149. configurable: true
  68150. });
  68151. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68152. /**
  68153. * If the depth of field is enabled.
  68154. */
  68155. get: function () {
  68156. return this._depthOfFieldEnabled;
  68157. },
  68158. set: function (enabled) {
  68159. if (this._depthOfFieldEnabled === enabled) {
  68160. return;
  68161. }
  68162. this._depthOfFieldEnabled = enabled;
  68163. this._buildPipeline();
  68164. },
  68165. enumerable: true,
  68166. configurable: true
  68167. });
  68168. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68169. /**
  68170. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68171. */
  68172. get: function () {
  68173. return this._depthOfFieldBlurLevel;
  68174. },
  68175. set: function (value) {
  68176. if (this._depthOfFieldBlurLevel === value) {
  68177. return;
  68178. }
  68179. this._depthOfFieldBlurLevel = value;
  68180. // recreate dof and dispose old as this setting is not dynamic
  68181. var oldDof = this.depthOfField;
  68182. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68183. this.depthOfField.focalLength = oldDof.focalLength;
  68184. this.depthOfField.focusDistance = oldDof.focusDistance;
  68185. this.depthOfField.fStop = oldDof.fStop;
  68186. this.depthOfField.lensSize = oldDof.lensSize;
  68187. for (var i = 0; i < this._cameras.length; i++) {
  68188. oldDof.disposeEffects(this._cameras[i]);
  68189. }
  68190. this._buildPipeline();
  68191. },
  68192. enumerable: true,
  68193. configurable: true
  68194. });
  68195. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68196. get: function () {
  68197. return this._fxaaEnabled;
  68198. },
  68199. /**
  68200. * If the anti aliasing is enabled.
  68201. */
  68202. set: function (enabled) {
  68203. if (this._fxaaEnabled === enabled) {
  68204. return;
  68205. }
  68206. this._fxaaEnabled = enabled;
  68207. this._buildPipeline();
  68208. },
  68209. enumerable: true,
  68210. configurable: true
  68211. });
  68212. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68213. get: function () {
  68214. return this._msaaEnabled;
  68215. },
  68216. /**
  68217. * If the multisample anti-aliasing is enabled.
  68218. */
  68219. set: function (enabled) {
  68220. if (this._msaaEnabled === enabled) {
  68221. return;
  68222. }
  68223. this._msaaEnabled = enabled;
  68224. this._buildPipeline();
  68225. },
  68226. enumerable: true,
  68227. configurable: true
  68228. });
  68229. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68230. get: function () {
  68231. return this._imageProcessingEnabled;
  68232. },
  68233. /**
  68234. * If image processing is enabled.
  68235. */
  68236. set: function (enabled) {
  68237. if (this._imageProcessingEnabled === enabled) {
  68238. return;
  68239. }
  68240. this._imageProcessingEnabled = enabled;
  68241. this._buildPipeline();
  68242. },
  68243. enumerable: true,
  68244. configurable: true
  68245. });
  68246. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68247. get: function () {
  68248. return this._chromaticAberrationEnabled;
  68249. },
  68250. /**
  68251. * Enable or disable the chromaticAberration process from the pipeline
  68252. */
  68253. set: function (enabled) {
  68254. if (this._chromaticAberrationEnabled === enabled) {
  68255. return;
  68256. }
  68257. this._chromaticAberrationEnabled = enabled;
  68258. this._buildPipeline();
  68259. },
  68260. enumerable: true,
  68261. configurable: true
  68262. });
  68263. /**
  68264. * Force the compilation of the entire pipeline.
  68265. */
  68266. DefaultRenderingPipeline.prototype.prepare = function () {
  68267. var previousState = this._buildAllowed;
  68268. this._buildAllowed = true;
  68269. this._buildPipeline();
  68270. this._buildAllowed = previousState;
  68271. };
  68272. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  68273. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  68274. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  68275. postProcess.autoClear = false;
  68276. }
  68277. else {
  68278. postProcess.autoClear = true;
  68279. }
  68280. if (!skipTextureSharing) {
  68281. if (this._prevPrevPostProcess) {
  68282. postProcess.shareOutputWith(this._prevPrevPostProcess);
  68283. }
  68284. else {
  68285. postProcess.useOwnOutput();
  68286. }
  68287. if (this._prevPostProcess) {
  68288. this._prevPrevPostProcess = this._prevPostProcess;
  68289. }
  68290. this._prevPostProcess = postProcess;
  68291. }
  68292. };
  68293. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68294. var _this = this;
  68295. if (!this._buildAllowed) {
  68296. return;
  68297. }
  68298. var engine = this._scene.getEngine();
  68299. this._disposePostProcesses();
  68300. if (this._cameras !== null) {
  68301. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68302. // get back cameras to be used to reattach pipeline
  68303. this._cameras = this._originalCameras.slice();
  68304. }
  68305. this._reset();
  68306. this._prevPostProcess = null;
  68307. this._prevPrevPostProcess = null;
  68308. if (this.fxaaEnabled) {
  68309. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68310. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68311. this._setAutoClearAndTextureSharing(this.fxaa);
  68312. }
  68313. if (this.sharpenEnabled) {
  68314. this.addEffect(this._sharpenEffect);
  68315. this._setAutoClearAndTextureSharing(this.sharpen);
  68316. }
  68317. if (this.depthOfFieldEnabled) {
  68318. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68319. this.depthOfField.depthTexture = depthTexture;
  68320. this.addEffect(this.depthOfField);
  68321. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  68322. }
  68323. if (this.bloomEnabled) {
  68324. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68325. this._setAutoClearAndTextureSharing(this.pass, true);
  68326. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68327. if (!this._hdr) {
  68328. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68329. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68330. this.highlights.autoClear = false;
  68331. this.highlights.alwaysForcePOT = true;
  68332. }
  68333. 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);
  68334. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68335. this.blurX.alwaysForcePOT = true;
  68336. this.blurX.autoClear = false;
  68337. this.blurX.onActivateObservable.add(function () {
  68338. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68339. _this.blurX.kernel = _this.bloomKernel * dw;
  68340. });
  68341. 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);
  68342. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68343. this.blurY.alwaysForcePOT = true;
  68344. this.blurY.autoClear = false;
  68345. this.blurY.onActivateObservable.add(function () {
  68346. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68347. _this.blurY.kernel = _this.bloomKernel * dh;
  68348. });
  68349. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68350. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68351. this.copyBack.alwaysForcePOT = true;
  68352. if (this._hdr) {
  68353. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68354. var w = this.bloomWeight;
  68355. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68356. }
  68357. else {
  68358. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68359. }
  68360. this.copyBack.autoClear = false;
  68361. }
  68362. if (this._imageProcessingEnabled) {
  68363. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68364. if (this._hdr) {
  68365. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68366. }
  68367. else {
  68368. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68369. }
  68370. }
  68371. if (this._hdr && this.imageProcessing) {
  68372. this.finalMerge = this.imageProcessing;
  68373. }
  68374. else {
  68375. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68376. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68377. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  68378. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68379. }
  68380. if (this.bloomEnabled) {
  68381. if (this._hdr) {
  68382. this.copyBack.shareOutputWith(this.blurX);
  68383. if (this.imageProcessing) {
  68384. this.imageProcessing.shareOutputWith(this.pass);
  68385. this.imageProcessing.autoClear = false;
  68386. }
  68387. else {
  68388. this.finalMerge.shareOutputWith(this.pass);
  68389. }
  68390. }
  68391. else {
  68392. this.finalMerge.shareOutputWith(this.pass);
  68393. }
  68394. }
  68395. if (this.chromaticAberrationEnabled) {
  68396. this.addEffect(this._chromaticAberrationEffect);
  68397. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  68398. }
  68399. if (this._cameras !== null) {
  68400. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68401. }
  68402. if (this.msaaEnabled) {
  68403. if (!this._enableMSAAOnFirstPostProcess()) {
  68404. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  68405. }
  68406. }
  68407. };
  68408. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  68409. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  68410. for (var i = 0; i < this._cameras.length; i++) {
  68411. var camera = this._cameras[i];
  68412. if (this.pass) {
  68413. this.pass.dispose(camera);
  68414. }
  68415. if (this.highlights) {
  68416. this.highlights.dispose(camera);
  68417. }
  68418. if (this.blurX) {
  68419. this.blurX.dispose(camera);
  68420. }
  68421. if (this.blurY) {
  68422. this.blurY.dispose(camera);
  68423. }
  68424. if (this.copyBack) {
  68425. this.copyBack.dispose(camera);
  68426. }
  68427. if (this.imageProcessing) {
  68428. this.imageProcessing.dispose(camera);
  68429. }
  68430. if (this.fxaa) {
  68431. this.fxaa.dispose(camera);
  68432. }
  68433. if (this.finalMerge) {
  68434. this.finalMerge.dispose(camera);
  68435. }
  68436. // These are created in the constructor and should not be disposed on every pipeline change
  68437. if (disposeNonRecreated) {
  68438. if (this.sharpen) {
  68439. this.sharpen.dispose(camera);
  68440. }
  68441. if (this.depthOfField) {
  68442. this.depthOfField.disposeEffects(camera);
  68443. }
  68444. if (this.chromaticAberration) {
  68445. this.chromaticAberration.dispose(camera);
  68446. }
  68447. }
  68448. }
  68449. this.pass = null;
  68450. this.highlights = null;
  68451. this.blurX = null;
  68452. this.blurY = null;
  68453. this.copyBack = null;
  68454. this.imageProcessing = null;
  68455. this.fxaa = null;
  68456. this.finalMerge = null;
  68457. if (disposeNonRecreated) {
  68458. this.sharpen = null;
  68459. this.depthOfField = null;
  68460. this.chromaticAberration = null;
  68461. }
  68462. };
  68463. /**
  68464. * Dispose of the pipeline and stop all post processes
  68465. */
  68466. DefaultRenderingPipeline.prototype.dispose = function () {
  68467. this._disposePostProcesses(true);
  68468. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68469. _super.prototype.dispose.call(this);
  68470. };
  68471. /**
  68472. * Serialize the rendering pipeline (Used when exporting)
  68473. * @returns the serialized object
  68474. */
  68475. DefaultRenderingPipeline.prototype.serialize = function () {
  68476. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68477. serializationObject.customType = "DefaultRenderingPipeline";
  68478. return serializationObject;
  68479. };
  68480. /**
  68481. * Parse the serialized pipeline
  68482. * @param source Source pipeline.
  68483. * @param scene The scene to load the pipeline to.
  68484. * @param rootUrl The URL of the serialized pipeline.
  68485. * @returns An instantiated pipeline from the serialized object.
  68486. */
  68487. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68488. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68489. };
  68490. __decorate([
  68491. BABYLON.serialize()
  68492. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  68493. __decorate([
  68494. BABYLON.serialize()
  68495. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68496. __decorate([
  68497. BABYLON.serialize()
  68498. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68499. __decorate([
  68500. BABYLON.serialize()
  68501. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68502. __decorate([
  68503. BABYLON.serialize()
  68504. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68505. __decorate([
  68506. BABYLON.serialize()
  68507. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68508. __decorate([
  68509. BABYLON.serialize()
  68510. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68511. __decorate([
  68512. BABYLON.serialize()
  68513. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68514. __decorate([
  68515. BABYLON.serialize()
  68516. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68517. __decorate([
  68518. BABYLON.serialize()
  68519. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68520. __decorate([
  68521. BABYLON.serialize()
  68522. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  68523. __decorate([
  68524. BABYLON.serialize()
  68525. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68526. __decorate([
  68527. BABYLON.serialize()
  68528. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  68529. return DefaultRenderingPipeline;
  68530. }(BABYLON.PostProcessRenderPipeline));
  68531. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68532. })(BABYLON || (BABYLON = {}));
  68533. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68534. var BABYLON;
  68535. (function (BABYLON) {
  68536. /**
  68537. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68538. */
  68539. var GeometryBufferRenderer = /** @class */ (function () {
  68540. /**
  68541. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68542. * @param scene The scene the buffer belongs to
  68543. * @param ratio How big is the buffer related to the main canvas.
  68544. */
  68545. function GeometryBufferRenderer(scene, ratio) {
  68546. if (ratio === void 0) { ratio = 1; }
  68547. this._enablePosition = false;
  68548. this._scene = scene;
  68549. this._ratio = ratio;
  68550. // Render target
  68551. this._createRenderTargets();
  68552. }
  68553. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68554. /**
  68555. * Set the render list (meshes to be rendered) used in the G buffer.
  68556. */
  68557. set: function (meshes) {
  68558. this._multiRenderTarget.renderList = meshes;
  68559. },
  68560. enumerable: true,
  68561. configurable: true
  68562. });
  68563. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68564. /**
  68565. * Gets wether or not G buffer are supported by the running hardware.
  68566. * This requires draw buffer supports
  68567. */
  68568. get: function () {
  68569. return this._multiRenderTarget.isSupported;
  68570. },
  68571. enumerable: true,
  68572. configurable: true
  68573. });
  68574. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68575. /**
  68576. * Gets wether or not position are enabled for the G buffer.
  68577. */
  68578. get: function () {
  68579. return this._enablePosition;
  68580. },
  68581. /**
  68582. * Sets wether or not position are enabled for the G buffer.
  68583. */
  68584. set: function (enable) {
  68585. this._enablePosition = enable;
  68586. this.dispose();
  68587. this._createRenderTargets();
  68588. },
  68589. enumerable: true,
  68590. configurable: true
  68591. });
  68592. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68593. /**
  68594. * Gets the scene associated with the buffer.
  68595. */
  68596. get: function () {
  68597. return this._scene;
  68598. },
  68599. enumerable: true,
  68600. configurable: true
  68601. });
  68602. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68603. /**
  68604. * Gets the ratio used by the buffer during its creation.
  68605. * How big is the buffer related to the main canvas.
  68606. */
  68607. get: function () {
  68608. return this._ratio;
  68609. },
  68610. enumerable: true,
  68611. configurable: true
  68612. });
  68613. /**
  68614. * Checks wether everything is ready to render a submesh to the G buffer.
  68615. * @param subMesh the submesh to check readiness for
  68616. * @param useInstances is the mesh drawn using instance or not
  68617. * @returns true if ready otherwise false
  68618. */
  68619. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68620. var material = subMesh.getMaterial();
  68621. if (material && material.disableDepthWrite) {
  68622. return false;
  68623. }
  68624. var defines = [];
  68625. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68626. var mesh = subMesh.getMesh();
  68627. // Alpha test
  68628. if (material && material.needAlphaTesting()) {
  68629. defines.push("#define ALPHATEST");
  68630. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68631. attribs.push(BABYLON.VertexBuffer.UVKind);
  68632. defines.push("#define UV1");
  68633. }
  68634. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68635. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68636. defines.push("#define UV2");
  68637. }
  68638. }
  68639. // Buffers
  68640. if (this._enablePosition) {
  68641. defines.push("#define POSITION");
  68642. }
  68643. // Bones
  68644. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68645. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68646. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68647. if (mesh.numBoneInfluencers > 4) {
  68648. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68649. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68650. }
  68651. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68652. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68653. }
  68654. else {
  68655. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68656. }
  68657. // Instances
  68658. if (useInstances) {
  68659. defines.push("#define INSTANCES");
  68660. attribs.push("world0");
  68661. attribs.push("world1");
  68662. attribs.push("world2");
  68663. attribs.push("world3");
  68664. }
  68665. // Get correct effect
  68666. var join = defines.join("\n");
  68667. if (this._cachedDefines !== join) {
  68668. this._cachedDefines = join;
  68669. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68670. }
  68671. return this._effect.isReady();
  68672. };
  68673. /**
  68674. * Gets the current underlying G Buffer.
  68675. * @returns the buffer
  68676. */
  68677. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68678. return this._multiRenderTarget;
  68679. };
  68680. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68681. /**
  68682. * Gets the number of samples used to render the buffer (anti aliasing).
  68683. */
  68684. get: function () {
  68685. return this._multiRenderTarget.samples;
  68686. },
  68687. /**
  68688. * Sets the number of samples used to render the buffer (anti aliasing).
  68689. */
  68690. set: function (value) {
  68691. this._multiRenderTarget.samples = value;
  68692. },
  68693. enumerable: true,
  68694. configurable: true
  68695. });
  68696. /**
  68697. * Disposes the renderer and frees up associated resources.
  68698. */
  68699. GeometryBufferRenderer.prototype.dispose = function () {
  68700. this.getGBuffer().dispose();
  68701. };
  68702. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68703. var _this = this;
  68704. var engine = this._scene.getEngine();
  68705. var count = this._enablePosition ? 3 : 2;
  68706. 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 });
  68707. if (!this.isSupported) {
  68708. return;
  68709. }
  68710. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68711. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68712. this._multiRenderTarget.refreshRate = 1;
  68713. this._multiRenderTarget.renderParticles = false;
  68714. this._multiRenderTarget.renderList = null;
  68715. // set default depth value to 1.0 (far away)
  68716. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68717. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68718. });
  68719. // Custom render function
  68720. var renderSubMesh = function (subMesh) {
  68721. var mesh = subMesh.getRenderingMesh();
  68722. var scene = _this._scene;
  68723. var engine = scene.getEngine();
  68724. var material = subMesh.getMaterial();
  68725. if (!material) {
  68726. return;
  68727. }
  68728. // Culling
  68729. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68730. // Managing instances
  68731. var batch = mesh._getInstancesRenderList(subMesh._id);
  68732. if (batch.mustReturn) {
  68733. return;
  68734. }
  68735. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68736. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68737. engine.enableEffect(_this._effect);
  68738. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68739. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68740. _this._effect.setMatrix("view", scene.getViewMatrix());
  68741. // Alpha test
  68742. if (material && material.needAlphaTesting()) {
  68743. var alphaTexture = material.getAlphaTestTexture();
  68744. if (alphaTexture) {
  68745. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68746. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68747. }
  68748. }
  68749. // Bones
  68750. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68751. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68752. }
  68753. // Draw
  68754. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68755. }
  68756. };
  68757. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68758. var index;
  68759. if (depthOnlySubMeshes.length) {
  68760. engine.setColorWrite(false);
  68761. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68762. renderSubMesh(depthOnlySubMeshes.data[index]);
  68763. }
  68764. engine.setColorWrite(true);
  68765. }
  68766. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68767. renderSubMesh(opaqueSubMeshes.data[index]);
  68768. }
  68769. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68770. renderSubMesh(alphaTestSubMeshes.data[index]);
  68771. }
  68772. };
  68773. };
  68774. return GeometryBufferRenderer;
  68775. }());
  68776. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68777. })(BABYLON || (BABYLON = {}));
  68778. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68779. var BABYLON;
  68780. (function (BABYLON) {
  68781. var RefractionPostProcess = /** @class */ (function (_super) {
  68782. __extends(RefractionPostProcess, _super);
  68783. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68784. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68785. _this.color = color;
  68786. _this.depth = depth;
  68787. _this.colorLevel = colorLevel;
  68788. _this._ownRefractionTexture = true;
  68789. _this.onActivateObservable.add(function (cam) {
  68790. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68791. });
  68792. _this.onApplyObservable.add(function (effect) {
  68793. effect.setColor3("baseColor", _this.color);
  68794. effect.setFloat("depth", _this.depth);
  68795. effect.setFloat("colorLevel", _this.colorLevel);
  68796. effect.setTexture("refractionSampler", _this._refTexture);
  68797. });
  68798. return _this;
  68799. }
  68800. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68801. /**
  68802. * Gets or sets the refraction texture
  68803. * Please note that you are responsible for disposing the texture if you set it manually
  68804. */
  68805. get: function () {
  68806. return this._refTexture;
  68807. },
  68808. set: function (value) {
  68809. if (this._refTexture && this._ownRefractionTexture) {
  68810. this._refTexture.dispose();
  68811. }
  68812. this._refTexture = value;
  68813. this._ownRefractionTexture = false;
  68814. },
  68815. enumerable: true,
  68816. configurable: true
  68817. });
  68818. // Methods
  68819. RefractionPostProcess.prototype.dispose = function (camera) {
  68820. if (this._refTexture && this._ownRefractionTexture) {
  68821. this._refTexture.dispose();
  68822. this._refTexture = null;
  68823. }
  68824. _super.prototype.dispose.call(this, camera);
  68825. };
  68826. return RefractionPostProcess;
  68827. }(BABYLON.PostProcess));
  68828. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68829. })(BABYLON || (BABYLON = {}));
  68830. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68831. var BABYLON;
  68832. (function (BABYLON) {
  68833. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68834. __extends(BlackAndWhitePostProcess, _super);
  68835. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68836. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68837. _this.degree = 1;
  68838. _this.onApplyObservable.add(function (effect) {
  68839. effect.setFloat("degree", _this.degree);
  68840. });
  68841. return _this;
  68842. }
  68843. return BlackAndWhitePostProcess;
  68844. }(BABYLON.PostProcess));
  68845. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68846. })(BABYLON || (BABYLON = {}));
  68847. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68848. var BABYLON;
  68849. (function (BABYLON) {
  68850. /**
  68851. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  68852. * input texture to perform effects such as edge detection or sharpening
  68853. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68854. */
  68855. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68856. __extends(ConvolutionPostProcess, _super);
  68857. /**
  68858. * Creates a new instance of @see ConvolutionPostProcess
  68859. * @param name The name of the effect.
  68860. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  68861. * @param options The required width/height ratio to downsize to before computing the render pass.
  68862. * @param camera The camera to apply the render pass to.
  68863. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68864. * @param engine The engine which the post process will be applied. (default: current engine)
  68865. * @param reusable If the post process can be reused on the same frame. (default: false)
  68866. * @param textureType Type of textures used when performing the post process. (default: 0)
  68867. */
  68868. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  68869. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68870. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68871. _this.kernel = kernel;
  68872. _this.onApply = function (effect) {
  68873. effect.setFloat2("screenSize", _this.width, _this.height);
  68874. effect.setArray("kernel", _this.kernel);
  68875. };
  68876. return _this;
  68877. }
  68878. // Statics
  68879. /**
  68880. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68881. */
  68882. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68883. /**
  68884. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68885. */
  68886. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68887. /**
  68888. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68889. */
  68890. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68891. /**
  68892. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68893. */
  68894. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68895. /**
  68896. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68897. */
  68898. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68899. /**
  68900. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68901. */
  68902. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68903. return ConvolutionPostProcess;
  68904. }(BABYLON.PostProcess));
  68905. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68906. })(BABYLON || (BABYLON = {}));
  68907. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68908. var BABYLON;
  68909. (function (BABYLON) {
  68910. /**
  68911. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68912. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68913. */
  68914. var SharpenPostProcess = /** @class */ (function (_super) {
  68915. __extends(SharpenPostProcess, _super);
  68916. /**
  68917. * Creates a new instance of @see ConvolutionPostProcess
  68918. * @param name The name of the effect.
  68919. * @param options The required width/height ratio to downsize to before computing the render pass.
  68920. * @param camera The camera to apply the render pass to.
  68921. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68922. * @param engine The engine which the post process will be applied. (default: current engine)
  68923. * @param reusable If the post process can be reused on the same frame. (default: false)
  68924. * @param textureType Type of textures used when performing the post process. (default: 0)
  68925. */
  68926. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68927. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68928. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68929. /**
  68930. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68931. */
  68932. _this.colorAmount = 1.0;
  68933. /**
  68934. * How much sharpness should be applied (default: 0.3)
  68935. */
  68936. _this.edgeAmount = 0.3;
  68937. _this.onApply = function (effect) {
  68938. effect.setFloat2("screenSize", _this.width, _this.height);
  68939. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68940. };
  68941. return _this;
  68942. }
  68943. return SharpenPostProcess;
  68944. }(BABYLON.PostProcess));
  68945. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68946. })(BABYLON || (BABYLON = {}));
  68947. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68948. var BABYLON;
  68949. (function (BABYLON) {
  68950. /**
  68951. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68952. */
  68953. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68954. __extends(ChromaticAberrationPostProcess, _super);
  68955. /**
  68956. * Creates a new instance of @see ChromaticAberrationPostProcess
  68957. * @param name The name of the effect.
  68958. * @param screenWidth The width of the screen to apply the effect on.
  68959. * @param screenHeight The height of the screen to apply the effect on.
  68960. * @param options The required width/height ratio to downsize to before computing the render pass.
  68961. * @param camera The camera to apply the render pass to.
  68962. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68963. * @param engine The engine which the post process will be applied. (default: current engine)
  68964. * @param reusable If the post process can be reused on the same frame. (default: false)
  68965. * @param textureType Type of textures used when performing the post process. (default: 0)
  68966. */
  68967. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType) {
  68968. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68969. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68970. /**
  68971. * The amount of seperation of rgb channels (default: 0)
  68972. */
  68973. _this.aberrationAmount = 0;
  68974. /**
  68975. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68976. */
  68977. _this.radialIntensity = 0;
  68978. /**
  68979. * 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))
  68980. */
  68981. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68982. /**
  68983. * 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))
  68984. */
  68985. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68986. _this.onApplyObservable.add(function (effect) {
  68987. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68988. effect.setFloat('screen_width', screenWidth);
  68989. effect.setFloat('screen_height', screenHeight);
  68990. effect.setFloat('radialIntensity', _this.radialIntensity);
  68991. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68992. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68993. });
  68994. return _this;
  68995. }
  68996. return ChromaticAberrationPostProcess;
  68997. }(BABYLON.PostProcess));
  68998. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68999. })(BABYLON || (BABYLON = {}));
  69000. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69001. var BABYLON;
  69002. (function (BABYLON) {
  69003. var FilterPostProcess = /** @class */ (function (_super) {
  69004. __extends(FilterPostProcess, _super);
  69005. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69006. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69007. _this.kernelMatrix = kernelMatrix;
  69008. _this.onApply = function (effect) {
  69009. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69010. };
  69011. return _this;
  69012. }
  69013. return FilterPostProcess;
  69014. }(BABYLON.PostProcess));
  69015. BABYLON.FilterPostProcess = FilterPostProcess;
  69016. })(BABYLON || (BABYLON = {}));
  69017. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69018. var BABYLON;
  69019. (function (BABYLON) {
  69020. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69021. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69022. __extends(VolumetricLightScatteringPostProcess, _super);
  69023. /**
  69024. * @constructor
  69025. * @param {string} name - The post-process name
  69026. * @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)
  69027. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69028. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69029. * @param {number} samples - The post-process quality, default 100
  69030. * @param {number} samplingMode - The post-process filtering mode
  69031. * @param {BABYLON.Engine} engine - The babylon engine
  69032. * @param {boolean} reusable - If the post-process is reusable
  69033. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69034. */
  69035. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69036. if (samples === void 0) { samples = 100; }
  69037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69038. 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;
  69039. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69040. /**
  69041. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69042. * @type {Vector3}
  69043. */
  69044. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69045. /**
  69046. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69047. * @type {boolean}
  69048. */
  69049. _this.useCustomMeshPosition = false;
  69050. /**
  69051. * If the post-process should inverse the light scattering direction
  69052. * @type {boolean}
  69053. */
  69054. _this.invert = true;
  69055. /**
  69056. * Array containing the excluded meshes not rendered in the internal pass
  69057. */
  69058. _this.excludedMeshes = new Array();
  69059. /**
  69060. * Controls the overall intensity of the post-process
  69061. * @type {number}
  69062. */
  69063. _this.exposure = 0.3;
  69064. /**
  69065. * Dissipates each sample's contribution in range [0, 1]
  69066. * @type {number}
  69067. */
  69068. _this.decay = 0.96815;
  69069. /**
  69070. * Controls the overall intensity of each sample
  69071. * @type {number}
  69072. */
  69073. _this.weight = 0.58767;
  69074. /**
  69075. * Controls the density of each sample
  69076. * @type {number}
  69077. */
  69078. _this.density = 0.926;
  69079. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69080. engine = scene.getEngine();
  69081. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69082. // Configure mesh
  69083. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69084. // Configure
  69085. _this._createPass(scene, ratio.passRatio || ratio);
  69086. _this.onActivate = function (camera) {
  69087. if (!_this.isSupported) {
  69088. _this.dispose(camera);
  69089. }
  69090. _this.onActivate = null;
  69091. };
  69092. _this.onApplyObservable.add(function (effect) {
  69093. _this._updateMeshScreenCoordinates(scene);
  69094. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69095. effect.setFloat("exposure", _this.exposure);
  69096. effect.setFloat("decay", _this.decay);
  69097. effect.setFloat("weight", _this.weight);
  69098. effect.setFloat("density", _this.density);
  69099. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69100. });
  69101. return _this;
  69102. }
  69103. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69104. get: function () {
  69105. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69106. return false;
  69107. },
  69108. set: function (useDiffuseColor) {
  69109. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69110. },
  69111. enumerable: true,
  69112. configurable: true
  69113. });
  69114. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69115. return "VolumetricLightScatteringPostProcess";
  69116. };
  69117. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69118. var mesh = subMesh.getMesh();
  69119. // Render this.mesh as default
  69120. if (mesh === this.mesh && mesh.material) {
  69121. return mesh.material.isReady(mesh);
  69122. }
  69123. var defines = [];
  69124. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69125. var material = subMesh.getMaterial();
  69126. // Alpha test
  69127. if (material) {
  69128. if (material.needAlphaTesting()) {
  69129. defines.push("#define ALPHATEST");
  69130. }
  69131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69132. attribs.push(BABYLON.VertexBuffer.UVKind);
  69133. defines.push("#define UV1");
  69134. }
  69135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69136. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69137. defines.push("#define UV2");
  69138. }
  69139. }
  69140. // Bones
  69141. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69142. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69143. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69144. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69145. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69146. }
  69147. else {
  69148. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69149. }
  69150. // Instances
  69151. if (useInstances) {
  69152. defines.push("#define INSTANCES");
  69153. attribs.push("world0");
  69154. attribs.push("world1");
  69155. attribs.push("world2");
  69156. attribs.push("world3");
  69157. }
  69158. // Get correct effect
  69159. var join = defines.join("\n");
  69160. if (this._cachedDefines !== join) {
  69161. this._cachedDefines = join;
  69162. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69163. }
  69164. return this._volumetricLightScatteringPass.isReady();
  69165. };
  69166. /**
  69167. * Sets the new light position for light scattering effect
  69168. * @param {BABYLON.Vector3} The new custom light position
  69169. */
  69170. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69171. this.customMeshPosition = position;
  69172. };
  69173. /**
  69174. * Returns the light position for light scattering effect
  69175. * @return {BABYLON.Vector3} The custom light position
  69176. */
  69177. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69178. return this.customMeshPosition;
  69179. };
  69180. /**
  69181. * Disposes the internal assets and detaches the post-process from the camera
  69182. */
  69183. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69184. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69185. if (rttIndex !== -1) {
  69186. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69187. }
  69188. this._volumetricLightScatteringRTT.dispose();
  69189. _super.prototype.dispose.call(this, camera);
  69190. };
  69191. /**
  69192. * Returns the render target texture used by the post-process
  69193. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69194. */
  69195. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69196. return this._volumetricLightScatteringRTT;
  69197. };
  69198. // Private methods
  69199. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69200. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69201. return true;
  69202. }
  69203. return false;
  69204. };
  69205. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69206. var _this = this;
  69207. var engine = scene.getEngine();
  69208. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69209. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69210. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69211. this._volumetricLightScatteringRTT.renderList = null;
  69212. this._volumetricLightScatteringRTT.renderParticles = false;
  69213. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69214. var camera = this.getCamera();
  69215. if (camera) {
  69216. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69217. }
  69218. else {
  69219. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69220. }
  69221. // Custom render function for submeshes
  69222. var renderSubMesh = function (subMesh) {
  69223. var mesh = subMesh.getRenderingMesh();
  69224. if (_this._meshExcluded(mesh)) {
  69225. return;
  69226. }
  69227. var material = subMesh.getMaterial();
  69228. if (!material) {
  69229. return;
  69230. }
  69231. var scene = mesh.getScene();
  69232. var engine = scene.getEngine();
  69233. // Culling
  69234. engine.setState(material.backFaceCulling);
  69235. // Managing instances
  69236. var batch = mesh._getInstancesRenderList(subMesh._id);
  69237. if (batch.mustReturn) {
  69238. return;
  69239. }
  69240. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69241. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69242. var effect = _this._volumetricLightScatteringPass;
  69243. if (mesh === _this.mesh) {
  69244. if (subMesh.effect) {
  69245. effect = subMesh.effect;
  69246. }
  69247. else {
  69248. effect = material.getEffect();
  69249. }
  69250. }
  69251. engine.enableEffect(effect);
  69252. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69253. if (mesh === _this.mesh) {
  69254. material.bind(mesh.getWorldMatrix(), mesh);
  69255. }
  69256. else {
  69257. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69258. // Alpha test
  69259. if (material && material.needAlphaTesting()) {
  69260. var alphaTexture = material.getAlphaTestTexture();
  69261. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69262. if (alphaTexture) {
  69263. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69264. }
  69265. }
  69266. // Bones
  69267. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69268. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69269. }
  69270. }
  69271. // Draw
  69272. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69273. }
  69274. };
  69275. // Render target texture callbacks
  69276. var savedSceneClearColor;
  69277. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69278. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69279. savedSceneClearColor = scene.clearColor;
  69280. scene.clearColor = sceneClearColor;
  69281. });
  69282. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69283. scene.clearColor = savedSceneClearColor;
  69284. });
  69285. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69286. var engine = scene.getEngine();
  69287. var index;
  69288. if (depthOnlySubMeshes.length) {
  69289. engine.setColorWrite(false);
  69290. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69291. renderSubMesh(depthOnlySubMeshes.data[index]);
  69292. }
  69293. engine.setColorWrite(true);
  69294. }
  69295. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69296. renderSubMesh(opaqueSubMeshes.data[index]);
  69297. }
  69298. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69299. renderSubMesh(alphaTestSubMeshes.data[index]);
  69300. }
  69301. if (transparentSubMeshes.length) {
  69302. // Sort sub meshes
  69303. for (index = 0; index < transparentSubMeshes.length; index++) {
  69304. var submesh = transparentSubMeshes.data[index];
  69305. var boundingInfo = submesh.getBoundingInfo();
  69306. if (boundingInfo && scene.activeCamera) {
  69307. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69308. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69309. }
  69310. }
  69311. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69312. sortedArray.sort(function (a, b) {
  69313. // Alpha index first
  69314. if (a._alphaIndex > b._alphaIndex) {
  69315. return 1;
  69316. }
  69317. if (a._alphaIndex < b._alphaIndex) {
  69318. return -1;
  69319. }
  69320. // Then distance to camera
  69321. if (a._distanceToCamera < b._distanceToCamera) {
  69322. return 1;
  69323. }
  69324. if (a._distanceToCamera > b._distanceToCamera) {
  69325. return -1;
  69326. }
  69327. return 0;
  69328. });
  69329. // Render sub meshes
  69330. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69331. for (index = 0; index < sortedArray.length; index++) {
  69332. renderSubMesh(sortedArray[index]);
  69333. }
  69334. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69335. }
  69336. };
  69337. };
  69338. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69339. var transform = scene.getTransformMatrix();
  69340. var meshPosition;
  69341. if (this.useCustomMeshPosition) {
  69342. meshPosition = this.customMeshPosition;
  69343. }
  69344. else if (this.attachedNode) {
  69345. meshPosition = this.attachedNode.position;
  69346. }
  69347. else {
  69348. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69349. }
  69350. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69351. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69352. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69353. if (this.invert)
  69354. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69355. };
  69356. // Static methods
  69357. /**
  69358. * Creates a default mesh for the Volumeric Light Scattering post-process
  69359. * @param {string} The mesh name
  69360. * @param {BABYLON.Scene} The scene where to create the mesh
  69361. * @return {BABYLON.Mesh} the default mesh
  69362. */
  69363. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69364. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69365. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69366. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69367. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69368. mesh.material = material;
  69369. return mesh;
  69370. };
  69371. __decorate([
  69372. BABYLON.serializeAsVector3()
  69373. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69374. __decorate([
  69375. BABYLON.serialize()
  69376. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69377. __decorate([
  69378. BABYLON.serialize()
  69379. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69380. __decorate([
  69381. BABYLON.serializeAsMeshReference()
  69382. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69383. __decorate([
  69384. BABYLON.serialize()
  69385. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69386. __decorate([
  69387. BABYLON.serialize()
  69388. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69389. __decorate([
  69390. BABYLON.serialize()
  69391. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69392. __decorate([
  69393. BABYLON.serialize()
  69394. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69395. __decorate([
  69396. BABYLON.serialize()
  69397. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69398. return VolumetricLightScatteringPostProcess;
  69399. }(BABYLON.PostProcess));
  69400. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69401. })(BABYLON || (BABYLON = {}));
  69402. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69403. //
  69404. // This post-process allows the modification of rendered colors by using
  69405. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69406. //
  69407. // The object needs to be provided an url to a texture containing the color
  69408. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69409. // Use an image editing software to tweak the LUT to match your needs.
  69410. //
  69411. // For an example of a color LUT, see here:
  69412. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69413. // For explanations on color grading, see here:
  69414. // http://udn.epicgames.com/Three/ColorGrading.html
  69415. //
  69416. var BABYLON;
  69417. (function (BABYLON) {
  69418. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69419. __extends(ColorCorrectionPostProcess, _super);
  69420. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69421. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69422. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69423. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69424. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69425. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69426. _this.onApply = function (effect) {
  69427. effect.setTexture("colorTable", _this._colorTableTexture);
  69428. };
  69429. return _this;
  69430. }
  69431. return ColorCorrectionPostProcess;
  69432. }(BABYLON.PostProcess));
  69433. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69434. })(BABYLON || (BABYLON = {}));
  69435. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69436. var BABYLON;
  69437. (function (BABYLON) {
  69438. var TonemappingOperator;
  69439. (function (TonemappingOperator) {
  69440. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69441. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69442. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69443. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69444. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69445. ;
  69446. var TonemapPostProcess = /** @class */ (function (_super) {
  69447. __extends(TonemapPostProcess, _super);
  69448. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69450. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69451. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69452. _this._operator = _operator;
  69453. _this.exposureAdjustment = exposureAdjustment;
  69454. var defines = "#define ";
  69455. if (_this._operator === TonemappingOperator.Hable)
  69456. defines += "HABLE_TONEMAPPING";
  69457. else if (_this._operator === TonemappingOperator.Reinhard)
  69458. defines += "REINHARD_TONEMAPPING";
  69459. else if (_this._operator === TonemappingOperator.HejiDawson)
  69460. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69461. else if (_this._operator === TonemappingOperator.Photographic)
  69462. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69463. //sadly a second call to create the effect.
  69464. _this.updateEffect(defines);
  69465. _this.onApply = function (effect) {
  69466. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69467. };
  69468. return _this;
  69469. }
  69470. return TonemapPostProcess;
  69471. }(BABYLON.PostProcess));
  69472. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69473. })(BABYLON || (BABYLON = {}));
  69474. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69475. var BABYLON;
  69476. (function (BABYLON) {
  69477. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69478. __extends(DisplayPassPostProcess, _super);
  69479. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69480. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69481. }
  69482. return DisplayPassPostProcess;
  69483. }(BABYLON.PostProcess));
  69484. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69485. })(BABYLON || (BABYLON = {}));
  69486. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69487. var BABYLON;
  69488. (function (BABYLON) {
  69489. var HighlightsPostProcess = /** @class */ (function (_super) {
  69490. __extends(HighlightsPostProcess, _super);
  69491. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69492. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69493. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69494. }
  69495. return HighlightsPostProcess;
  69496. }(BABYLON.PostProcess));
  69497. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69498. })(BABYLON || (BABYLON = {}));
  69499. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69500. var BABYLON;
  69501. (function (BABYLON) {
  69502. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69503. __extends(ImageProcessingPostProcess, _super);
  69504. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69505. if (camera === void 0) { camera = null; }
  69506. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69507. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69508. _this._fromLinearSpace = true;
  69509. /**
  69510. * Defines cache preventing GC.
  69511. */
  69512. _this._defines = {
  69513. IMAGEPROCESSING: false,
  69514. VIGNETTE: false,
  69515. VIGNETTEBLENDMODEMULTIPLY: false,
  69516. VIGNETTEBLENDMODEOPAQUE: false,
  69517. TONEMAPPING: false,
  69518. CONTRAST: false,
  69519. COLORCURVES: false,
  69520. COLORGRADING: false,
  69521. COLORGRADING3D: false,
  69522. FROMLINEARSPACE: false,
  69523. SAMPLER3DGREENDEPTH: false,
  69524. SAMPLER3DBGRMAP: false,
  69525. IMAGEPROCESSINGPOSTPROCESS: false,
  69526. EXPOSURE: false,
  69527. GRAIN: false,
  69528. };
  69529. // Setup the configuration as forced by the constructor. This would then not force the
  69530. // scene materials output in linear space and let untouched the default forward pass.
  69531. if (imageProcessingConfiguration) {
  69532. imageProcessingConfiguration.applyByPostProcess = true;
  69533. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69534. // This will cause the shader to be compiled
  69535. _this.fromLinearSpace = false;
  69536. }
  69537. else {
  69538. _this._attachImageProcessingConfiguration(null, true);
  69539. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69540. }
  69541. _this.onApply = function (effect) {
  69542. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69543. };
  69544. return _this;
  69545. }
  69546. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69547. /**
  69548. * Gets the image processing configuration used either in this material.
  69549. */
  69550. get: function () {
  69551. return this._imageProcessingConfiguration;
  69552. },
  69553. /**
  69554. * Sets the Default image processing configuration used either in the this material.
  69555. *
  69556. * If sets to null, the scene one is in use.
  69557. */
  69558. set: function (value) {
  69559. this._attachImageProcessingConfiguration(value);
  69560. },
  69561. enumerable: true,
  69562. configurable: true
  69563. });
  69564. /**
  69565. * Attaches a new image processing configuration to the PBR Material.
  69566. * @param configuration
  69567. */
  69568. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69569. var _this = this;
  69570. if (doNotBuild === void 0) { doNotBuild = false; }
  69571. if (configuration === this._imageProcessingConfiguration) {
  69572. return;
  69573. }
  69574. // Detaches observer.
  69575. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69576. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69577. }
  69578. // Pick the scene configuration if needed.
  69579. if (!configuration) {
  69580. var scene = null;
  69581. var engine = this.getEngine();
  69582. var camera = this.getCamera();
  69583. if (camera) {
  69584. scene = camera.getScene();
  69585. }
  69586. else if (engine && engine.scenes) {
  69587. var scenes = engine.scenes;
  69588. scene = scenes[scenes.length - 1];
  69589. }
  69590. else {
  69591. scene = BABYLON.Engine.LastCreatedScene;
  69592. }
  69593. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69594. }
  69595. else {
  69596. this._imageProcessingConfiguration = configuration;
  69597. }
  69598. // Attaches observer.
  69599. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69600. _this._updateParameters();
  69601. });
  69602. // Ensure the effect will be rebuilt.
  69603. if (!doNotBuild) {
  69604. this._updateParameters();
  69605. }
  69606. };
  69607. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69608. /**
  69609. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69610. */
  69611. get: function () {
  69612. return this.imageProcessingConfiguration.colorCurves;
  69613. },
  69614. /**
  69615. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69616. */
  69617. set: function (value) {
  69618. this.imageProcessingConfiguration.colorCurves = value;
  69619. },
  69620. enumerable: true,
  69621. configurable: true
  69622. });
  69623. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69624. /**
  69625. * Gets wether the color curves effect is enabled.
  69626. */
  69627. get: function () {
  69628. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69629. },
  69630. /**
  69631. * Sets wether the color curves effect is enabled.
  69632. */
  69633. set: function (value) {
  69634. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69635. },
  69636. enumerable: true,
  69637. configurable: true
  69638. });
  69639. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69640. /**
  69641. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69642. */
  69643. get: function () {
  69644. return this.imageProcessingConfiguration.colorGradingTexture;
  69645. },
  69646. /**
  69647. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69648. */
  69649. set: function (value) {
  69650. this.imageProcessingConfiguration.colorGradingTexture = value;
  69651. },
  69652. enumerable: true,
  69653. configurable: true
  69654. });
  69655. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69656. /**
  69657. * Gets wether the color grading effect is enabled.
  69658. */
  69659. get: function () {
  69660. return this.imageProcessingConfiguration.colorGradingEnabled;
  69661. },
  69662. /**
  69663. * Gets wether the color grading effect is enabled.
  69664. */
  69665. set: function (value) {
  69666. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69667. },
  69668. enumerable: true,
  69669. configurable: true
  69670. });
  69671. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69672. /**
  69673. * Gets exposure used in the effect.
  69674. */
  69675. get: function () {
  69676. return this.imageProcessingConfiguration.exposure;
  69677. },
  69678. /**
  69679. * Sets exposure used in the effect.
  69680. */
  69681. set: function (value) {
  69682. this.imageProcessingConfiguration.exposure = value;
  69683. },
  69684. enumerable: true,
  69685. configurable: true
  69686. });
  69687. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69688. /**
  69689. * Gets wether tonemapping is enabled or not.
  69690. */
  69691. get: function () {
  69692. return this._imageProcessingConfiguration.toneMappingEnabled;
  69693. },
  69694. /**
  69695. * Sets wether tonemapping is enabled or not
  69696. */
  69697. set: function (value) {
  69698. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69699. },
  69700. enumerable: true,
  69701. configurable: true
  69702. });
  69703. ;
  69704. ;
  69705. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69706. /**
  69707. * Gets contrast used in the effect.
  69708. */
  69709. get: function () {
  69710. return this.imageProcessingConfiguration.contrast;
  69711. },
  69712. /**
  69713. * Sets contrast used in the effect.
  69714. */
  69715. set: function (value) {
  69716. this.imageProcessingConfiguration.contrast = value;
  69717. },
  69718. enumerable: true,
  69719. configurable: true
  69720. });
  69721. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69722. /**
  69723. * Gets Vignette stretch size.
  69724. */
  69725. get: function () {
  69726. return this.imageProcessingConfiguration.vignetteStretch;
  69727. },
  69728. /**
  69729. * Sets Vignette stretch size.
  69730. */
  69731. set: function (value) {
  69732. this.imageProcessingConfiguration.vignetteStretch = value;
  69733. },
  69734. enumerable: true,
  69735. configurable: true
  69736. });
  69737. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69738. /**
  69739. * Gets Vignette centre X Offset.
  69740. */
  69741. get: function () {
  69742. return this.imageProcessingConfiguration.vignetteCentreX;
  69743. },
  69744. /**
  69745. * Sets Vignette centre X Offset.
  69746. */
  69747. set: function (value) {
  69748. this.imageProcessingConfiguration.vignetteCentreX = value;
  69749. },
  69750. enumerable: true,
  69751. configurable: true
  69752. });
  69753. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69754. /**
  69755. * Gets Vignette centre Y Offset.
  69756. */
  69757. get: function () {
  69758. return this.imageProcessingConfiguration.vignetteCentreY;
  69759. },
  69760. /**
  69761. * Sets Vignette centre Y Offset.
  69762. */
  69763. set: function (value) {
  69764. this.imageProcessingConfiguration.vignetteCentreY = value;
  69765. },
  69766. enumerable: true,
  69767. configurable: true
  69768. });
  69769. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69770. /**
  69771. * Gets Vignette weight or intensity of the vignette effect.
  69772. */
  69773. get: function () {
  69774. return this.imageProcessingConfiguration.vignetteWeight;
  69775. },
  69776. /**
  69777. * Sets Vignette weight or intensity of the vignette effect.
  69778. */
  69779. set: function (value) {
  69780. this.imageProcessingConfiguration.vignetteWeight = value;
  69781. },
  69782. enumerable: true,
  69783. configurable: true
  69784. });
  69785. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69786. /**
  69787. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69788. * if vignetteEnabled is set to true.
  69789. */
  69790. get: function () {
  69791. return this.imageProcessingConfiguration.vignetteColor;
  69792. },
  69793. /**
  69794. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69795. * if vignetteEnabled is set to true.
  69796. */
  69797. set: function (value) {
  69798. this.imageProcessingConfiguration.vignetteColor = value;
  69799. },
  69800. enumerable: true,
  69801. configurable: true
  69802. });
  69803. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69804. /**
  69805. * Gets Camera field of view used by the Vignette effect.
  69806. */
  69807. get: function () {
  69808. return this.imageProcessingConfiguration.vignetteCameraFov;
  69809. },
  69810. /**
  69811. * Sets Camera field of view used by the Vignette effect.
  69812. */
  69813. set: function (value) {
  69814. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69815. },
  69816. enumerable: true,
  69817. configurable: true
  69818. });
  69819. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69820. /**
  69821. * Gets the vignette blend mode allowing different kind of effect.
  69822. */
  69823. get: function () {
  69824. return this.imageProcessingConfiguration.vignetteBlendMode;
  69825. },
  69826. /**
  69827. * Sets the vignette blend mode allowing different kind of effect.
  69828. */
  69829. set: function (value) {
  69830. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69831. },
  69832. enumerable: true,
  69833. configurable: true
  69834. });
  69835. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69836. /**
  69837. * Gets wether the vignette effect is enabled.
  69838. */
  69839. get: function () {
  69840. return this.imageProcessingConfiguration.vignetteEnabled;
  69841. },
  69842. /**
  69843. * Sets wether the vignette effect is enabled.
  69844. */
  69845. set: function (value) {
  69846. this.imageProcessingConfiguration.vignetteEnabled = value;
  69847. },
  69848. enumerable: true,
  69849. configurable: true
  69850. });
  69851. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  69852. /**
  69853. * Gets wether the grain effect is enabled.
  69854. */
  69855. get: function () {
  69856. return this.imageProcessingConfiguration.grainEnabled;
  69857. },
  69858. /**
  69859. * Sets wether the grain effect is enabled.
  69860. */
  69861. set: function (value) {
  69862. this.imageProcessingConfiguration.grainEnabled = value;
  69863. },
  69864. enumerable: true,
  69865. configurable: true
  69866. });
  69867. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  69868. /**
  69869. * Gets the grain effect's intensity.
  69870. */
  69871. get: function () {
  69872. return this.imageProcessingConfiguration.grainIntensity;
  69873. },
  69874. /**
  69875. * Sets the grain effect's intensity.
  69876. */
  69877. set: function (value) {
  69878. this.imageProcessingConfiguration.grainIntensity = value;
  69879. },
  69880. enumerable: true,
  69881. configurable: true
  69882. });
  69883. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  69884. /**
  69885. * Gets wether the grain effect is animated.
  69886. */
  69887. get: function () {
  69888. return this.imageProcessingConfiguration.grainAnimated;
  69889. },
  69890. /**
  69891. * Sets wether the grain effect is animated.
  69892. */
  69893. set: function (value) {
  69894. this.imageProcessingConfiguration.grainAnimated = value;
  69895. },
  69896. enumerable: true,
  69897. configurable: true
  69898. });
  69899. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69900. /**
  69901. * Gets wether the input of the processing is in Gamma or Linear Space.
  69902. */
  69903. get: function () {
  69904. return this._fromLinearSpace;
  69905. },
  69906. /**
  69907. * Sets wether the input of the processing is in Gamma or Linear Space.
  69908. */
  69909. set: function (value) {
  69910. if (this._fromLinearSpace === value) {
  69911. return;
  69912. }
  69913. this._fromLinearSpace = value;
  69914. this._updateParameters();
  69915. },
  69916. enumerable: true,
  69917. configurable: true
  69918. });
  69919. ImageProcessingPostProcess.prototype.getClassName = function () {
  69920. return "ImageProcessingPostProcess";
  69921. };
  69922. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69923. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69924. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69925. var defines = "";
  69926. for (var define in this._defines) {
  69927. if (this._defines[define]) {
  69928. defines += "#define " + define + ";\r\n";
  69929. }
  69930. }
  69931. var samplers = ["textureSampler"];
  69932. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69933. var uniforms = ["scale"];
  69934. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69935. this.updateEffect(defines, uniforms, samplers);
  69936. };
  69937. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69938. _super.prototype.dispose.call(this, camera);
  69939. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69940. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69941. }
  69942. this.imageProcessingConfiguration.applyByPostProcess = false;
  69943. };
  69944. __decorate([
  69945. BABYLON.serialize()
  69946. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69947. return ImageProcessingPostProcess;
  69948. }(BABYLON.PostProcess));
  69949. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69950. })(BABYLON || (BABYLON = {}));
  69951. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69952. var BABYLON;
  69953. (function (BABYLON) {
  69954. /**
  69955. * The Blur Post Process which blurs an image based on a kernel and direction.
  69956. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69957. */
  69958. var BlurPostProcess = /** @class */ (function (_super) {
  69959. __extends(BlurPostProcess, _super);
  69960. /**
  69961. * Creates a new instance of @see BlurPostProcess
  69962. * @param name The name of the effect.
  69963. * @param direction The direction in which to blur the image.
  69964. * @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.
  69965. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69966. * @param camera The camera to apply the render pass to.
  69967. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69968. * @param engine The engine which the post process will be applied. (default: current engine)
  69969. * @param reusable If the post process can be reused on the same frame. (default: false)
  69970. * @param textureType Type of textures used when performing the post process. (default: 0)
  69971. */
  69972. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69974. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69975. if (defines === void 0) { defines = ""; }
  69976. 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;
  69977. _this.direction = direction;
  69978. _this._packedFloat = false;
  69979. _this._staticDefines = "";
  69980. _this._staticDefines = defines;
  69981. _this.onApplyObservable.add(function (effect) {
  69982. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69983. });
  69984. _this.kernel = kernel;
  69985. return _this;
  69986. }
  69987. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69988. /**
  69989. * Gets the length in pixels of the blur sample region
  69990. */
  69991. get: function () {
  69992. return this._idealKernel;
  69993. },
  69994. /**
  69995. * Sets the length in pixels of the blur sample region
  69996. */
  69997. set: function (v) {
  69998. if (this._idealKernel === v) {
  69999. return;
  70000. }
  70001. v = Math.max(v, 1);
  70002. this._idealKernel = v;
  70003. this._kernel = this._nearestBestKernel(v);
  70004. this._updateParameters();
  70005. },
  70006. enumerable: true,
  70007. configurable: true
  70008. });
  70009. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70010. /**
  70011. * Gets wether or not the blur is unpacking/repacking floats
  70012. */
  70013. get: function () {
  70014. return this._packedFloat;
  70015. },
  70016. /**
  70017. * Sets wether or not the blur needs to unpack/repack floats
  70018. */
  70019. set: function (v) {
  70020. if (this._packedFloat === v) {
  70021. return;
  70022. }
  70023. this._packedFloat = v;
  70024. this._updateParameters();
  70025. },
  70026. enumerable: true,
  70027. configurable: true
  70028. });
  70029. BlurPostProcess.prototype._updateParameters = function () {
  70030. // Generate sampling offsets and weights
  70031. var N = this._kernel;
  70032. var centerIndex = (N - 1) / 2;
  70033. // Generate Gaussian sampling weights over kernel
  70034. var offsets = [];
  70035. var weights = [];
  70036. var totalWeight = 0;
  70037. for (var i = 0; i < N; i++) {
  70038. var u = i / (N - 1);
  70039. var w = this._gaussianWeight(u * 2.0 - 1);
  70040. offsets[i] = (i - centerIndex);
  70041. weights[i] = w;
  70042. totalWeight += w;
  70043. }
  70044. // Normalize weights
  70045. for (var i = 0; i < weights.length; i++) {
  70046. weights[i] /= totalWeight;
  70047. }
  70048. // Optimize: combine samples to take advantage of hardware linear sampling
  70049. // Walk from left to center, combining pairs (symmetrically)
  70050. var linearSamplingWeights = [];
  70051. var linearSamplingOffsets = [];
  70052. var linearSamplingMap = [];
  70053. for (var i = 0; i <= centerIndex; i += 2) {
  70054. var j = Math.min(i + 1, Math.floor(centerIndex));
  70055. var singleCenterSample = i === j;
  70056. if (singleCenterSample) {
  70057. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70058. }
  70059. else {
  70060. var sharedCell = j === centerIndex;
  70061. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70062. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70063. if (offsetLinear === 0) {
  70064. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70065. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70066. }
  70067. else {
  70068. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70069. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70070. }
  70071. }
  70072. }
  70073. for (var i = 0; i < linearSamplingMap.length; i++) {
  70074. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70075. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70076. }
  70077. // Replace with optimized
  70078. offsets = linearSamplingOffsets;
  70079. weights = linearSamplingWeights;
  70080. // Generate shaders
  70081. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70082. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70083. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70084. var defines = "";
  70085. defines += this._staticDefines;
  70086. for (var i = 0; i < varyingCount; i++) {
  70087. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70088. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70089. }
  70090. var depCount = 0;
  70091. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70092. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70093. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70094. depCount++;
  70095. }
  70096. if (this.packedFloat) {
  70097. defines += "#define PACKEDFLOAT 1";
  70098. }
  70099. this.updateEffect(defines, null, null, {
  70100. varyingCount: varyingCount,
  70101. depCount: depCount
  70102. });
  70103. };
  70104. /**
  70105. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70106. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70107. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70108. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70109. * The gaps between physical kernels are compensated for in the weighting of the samples
  70110. * @param idealKernel Ideal blur kernel.
  70111. * @return Nearest best kernel.
  70112. */
  70113. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70114. var v = Math.round(idealKernel);
  70115. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70116. var k = _a[_i];
  70117. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70118. return Math.max(k, 3);
  70119. }
  70120. }
  70121. return Math.max(v, 3);
  70122. };
  70123. /**
  70124. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70125. * @param x The point on the Gaussian distribution to sample.
  70126. * @return the value of the Gaussian function at x.
  70127. */
  70128. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70129. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70130. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70131. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70132. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70133. // truncated at around 1.3% of peak strength.
  70134. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70135. var sigma = (1 / 3);
  70136. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70137. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70138. var weight = (1.0 / denominator) * Math.exp(exponent);
  70139. return weight;
  70140. };
  70141. /**
  70142. * Generates a string that can be used as a floating point number in GLSL.
  70143. * @param x Value to print.
  70144. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70145. * @return GLSL float string.
  70146. */
  70147. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70148. if (decimalFigures === void 0) { decimalFigures = 8; }
  70149. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70150. };
  70151. return BlurPostProcess;
  70152. }(BABYLON.PostProcess));
  70153. BABYLON.BlurPostProcess = BlurPostProcess;
  70154. })(BABYLON || (BABYLON = {}));
  70155. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70156. var BABYLON;
  70157. (function (BABYLON) {
  70158. var Bone = /** @class */ (function (_super) {
  70159. __extends(Bone, _super);
  70160. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70161. if (parentBone === void 0) { parentBone = null; }
  70162. if (localMatrix === void 0) { localMatrix = null; }
  70163. if (restPose === void 0) { restPose = null; }
  70164. if (baseMatrix === void 0) { baseMatrix = null; }
  70165. if (index === void 0) { index = null; }
  70166. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70167. _this.name = name;
  70168. _this.children = new Array();
  70169. _this.animations = new Array();
  70170. // Set this value to map this bone to a different index in the transform matrices.
  70171. // Set this value to -1 to exclude the bone from the transform matrices.
  70172. _this._index = null;
  70173. _this._worldTransform = new BABYLON.Matrix();
  70174. _this._absoluteTransform = new BABYLON.Matrix();
  70175. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70176. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70177. _this._scaleVector = BABYLON.Vector3.One();
  70178. _this._negateScaleChildren = BABYLON.Vector3.One();
  70179. _this._scalingDeterminant = 1;
  70180. _this._skeleton = skeleton;
  70181. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70182. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70183. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70184. _this._index = index;
  70185. skeleton.bones.push(_this);
  70186. _this.setParent(parentBone, false);
  70187. _this._updateDifferenceMatrix();
  70188. return _this;
  70189. }
  70190. Object.defineProperty(Bone.prototype, "_matrix", {
  70191. get: function () {
  70192. return this._localMatrix;
  70193. },
  70194. set: function (val) {
  70195. if (this._localMatrix) {
  70196. this._localMatrix.copyFrom(val);
  70197. }
  70198. else {
  70199. this._localMatrix = val;
  70200. }
  70201. },
  70202. enumerable: true,
  70203. configurable: true
  70204. });
  70205. // Members
  70206. Bone.prototype.getSkeleton = function () {
  70207. return this._skeleton;
  70208. };
  70209. Bone.prototype.getParent = function () {
  70210. return this._parent;
  70211. };
  70212. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70213. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70214. if (this._parent === parent) {
  70215. return;
  70216. }
  70217. if (this._parent) {
  70218. var index = this._parent.children.indexOf(this);
  70219. if (index !== -1) {
  70220. this._parent.children.splice(index, 1);
  70221. }
  70222. }
  70223. this._parent = parent;
  70224. if (this._parent) {
  70225. this._parent.children.push(this);
  70226. }
  70227. if (updateDifferenceMatrix) {
  70228. this._updateDifferenceMatrix();
  70229. }
  70230. };
  70231. Bone.prototype.getLocalMatrix = function () {
  70232. return this._localMatrix;
  70233. };
  70234. Bone.prototype.getBaseMatrix = function () {
  70235. return this._baseMatrix;
  70236. };
  70237. Bone.prototype.getRestPose = function () {
  70238. return this._restPose;
  70239. };
  70240. Bone.prototype.returnToRest = function () {
  70241. this.updateMatrix(this._restPose.clone());
  70242. };
  70243. Bone.prototype.getWorldMatrix = function () {
  70244. return this._worldTransform;
  70245. };
  70246. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70247. return this._invertedAbsoluteTransform;
  70248. };
  70249. Bone.prototype.getAbsoluteTransform = function () {
  70250. return this._absoluteTransform;
  70251. };
  70252. Object.defineProperty(Bone.prototype, "position", {
  70253. // Properties (matches AbstractMesh properties)
  70254. get: function () {
  70255. return this.getPosition();
  70256. },
  70257. set: function (newPosition) {
  70258. this.setPosition(newPosition);
  70259. },
  70260. enumerable: true,
  70261. configurable: true
  70262. });
  70263. Object.defineProperty(Bone.prototype, "rotation", {
  70264. get: function () {
  70265. return this.getRotation();
  70266. },
  70267. set: function (newRotation) {
  70268. this.setRotation(newRotation);
  70269. },
  70270. enumerable: true,
  70271. configurable: true
  70272. });
  70273. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70274. get: function () {
  70275. return this.getRotationQuaternion();
  70276. },
  70277. set: function (newRotation) {
  70278. this.setRotationQuaternion(newRotation);
  70279. },
  70280. enumerable: true,
  70281. configurable: true
  70282. });
  70283. Object.defineProperty(Bone.prototype, "scaling", {
  70284. get: function () {
  70285. return this.getScale();
  70286. },
  70287. set: function (newScaling) {
  70288. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70289. },
  70290. enumerable: true,
  70291. configurable: true
  70292. });
  70293. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70294. /**
  70295. * Gets the animation properties override
  70296. */
  70297. get: function () {
  70298. return this._skeleton.animationPropertiesOverride;
  70299. },
  70300. enumerable: true,
  70301. configurable: true
  70302. });
  70303. // Methods
  70304. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70305. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70306. this._baseMatrix = matrix.clone();
  70307. this._localMatrix = matrix.clone();
  70308. this._skeleton._markAsDirty();
  70309. if (updateDifferenceMatrix) {
  70310. this._updateDifferenceMatrix();
  70311. }
  70312. };
  70313. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70314. if (!rootMatrix) {
  70315. rootMatrix = this._baseMatrix;
  70316. }
  70317. if (this._parent) {
  70318. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70319. }
  70320. else {
  70321. this._absoluteTransform.copyFrom(rootMatrix);
  70322. }
  70323. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70324. for (var index = 0; index < this.children.length; index++) {
  70325. this.children[index]._updateDifferenceMatrix();
  70326. }
  70327. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70328. };
  70329. Bone.prototype.markAsDirty = function () {
  70330. this._currentRenderId++;
  70331. this._skeleton._markAsDirty();
  70332. };
  70333. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70334. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70335. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70336. // all animation may be coming from a library skeleton, so may need to create animation
  70337. if (this.animations.length === 0) {
  70338. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70339. this.animations[0].setKeys([]);
  70340. }
  70341. // get animation info / verify there is such a range from the source bone
  70342. var sourceRange = source.animations[0].getRange(rangeName);
  70343. if (!sourceRange) {
  70344. return false;
  70345. }
  70346. var from = sourceRange.from;
  70347. var to = sourceRange.to;
  70348. var sourceKeys = source.animations[0].getKeys();
  70349. // rescaling prep
  70350. var sourceBoneLength = source.length;
  70351. var sourceParent = source.getParent();
  70352. var parent = this.getParent();
  70353. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70354. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70355. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70356. var destKeys = this.animations[0].getKeys();
  70357. // loop vars declaration
  70358. var orig;
  70359. var origTranslation;
  70360. var mat;
  70361. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70362. orig = sourceKeys[key];
  70363. if (orig.frame >= from && orig.frame <= to) {
  70364. if (rescaleAsRequired) {
  70365. mat = orig.value.clone();
  70366. // scale based on parent ratio, when bone has parent
  70367. if (parentScalingReqd) {
  70368. origTranslation = mat.getTranslation();
  70369. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70370. // scale based on skeleton dimension ratio when root bone, and value is passed
  70371. }
  70372. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70373. origTranslation = mat.getTranslation();
  70374. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70375. // use original when root bone, and no data for skelDimensionsRatio
  70376. }
  70377. else {
  70378. mat = orig.value;
  70379. }
  70380. }
  70381. else {
  70382. mat = orig.value;
  70383. }
  70384. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70385. }
  70386. }
  70387. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70388. return true;
  70389. };
  70390. /**
  70391. * Translate the bone in local or world space.
  70392. * @param vec The amount to translate the bone.
  70393. * @param space The space that the translation is in.
  70394. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70395. */
  70396. Bone.prototype.translate = function (vec, space, mesh) {
  70397. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70398. var lm = this.getLocalMatrix();
  70399. if (space == BABYLON.Space.LOCAL) {
  70400. lm.m[12] += vec.x;
  70401. lm.m[13] += vec.y;
  70402. lm.m[14] += vec.z;
  70403. }
  70404. else {
  70405. var wm = null;
  70406. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70407. if (mesh) {
  70408. wm = mesh.getWorldMatrix();
  70409. }
  70410. this._skeleton.computeAbsoluteTransforms();
  70411. var tmat = Bone._tmpMats[0];
  70412. var tvec = Bone._tmpVecs[0];
  70413. if (this._parent) {
  70414. if (mesh && wm) {
  70415. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70416. tmat.multiplyToRef(wm, tmat);
  70417. }
  70418. else {
  70419. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70420. }
  70421. }
  70422. tmat.m[12] = 0;
  70423. tmat.m[13] = 0;
  70424. tmat.m[14] = 0;
  70425. tmat.invert();
  70426. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70427. lm.m[12] += tvec.x;
  70428. lm.m[13] += tvec.y;
  70429. lm.m[14] += tvec.z;
  70430. }
  70431. this.markAsDirty();
  70432. };
  70433. /**
  70434. * Set the postion of the bone in local or world space.
  70435. * @param position The position to set the bone.
  70436. * @param space The space that the position is in.
  70437. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70438. */
  70439. Bone.prototype.setPosition = function (position, space, mesh) {
  70440. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70441. var lm = this.getLocalMatrix();
  70442. if (space == BABYLON.Space.LOCAL) {
  70443. lm.m[12] = position.x;
  70444. lm.m[13] = position.y;
  70445. lm.m[14] = position.z;
  70446. }
  70447. else {
  70448. var wm = null;
  70449. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70450. if (mesh) {
  70451. wm = mesh.getWorldMatrix();
  70452. }
  70453. this._skeleton.computeAbsoluteTransforms();
  70454. var tmat = Bone._tmpMats[0];
  70455. var vec = Bone._tmpVecs[0];
  70456. if (this._parent) {
  70457. if (mesh && wm) {
  70458. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70459. tmat.multiplyToRef(wm, tmat);
  70460. }
  70461. else {
  70462. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70463. }
  70464. }
  70465. tmat.invert();
  70466. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70467. lm.m[12] = vec.x;
  70468. lm.m[13] = vec.y;
  70469. lm.m[14] = vec.z;
  70470. }
  70471. this.markAsDirty();
  70472. };
  70473. /**
  70474. * Set the absolute postion of the bone (world space).
  70475. * @param position The position to set the bone.
  70476. * @param mesh The mesh that this bone is attached to.
  70477. */
  70478. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70479. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70480. };
  70481. /**
  70482. * Set the scale of the bone on the x, y and z axes.
  70483. * @param x The scale of the bone on the x axis.
  70484. * @param x The scale of the bone on the y axis.
  70485. * @param z The scale of the bone on the z axis.
  70486. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70487. */
  70488. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70489. if (scaleChildren === void 0) { scaleChildren = false; }
  70490. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70491. if (!scaleChildren) {
  70492. this._negateScaleChildren.x = 1 / x;
  70493. this._negateScaleChildren.y = 1 / y;
  70494. this._negateScaleChildren.z = 1 / z;
  70495. }
  70496. this._syncScaleVector();
  70497. }
  70498. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70499. };
  70500. /**
  70501. * Scale the bone on the x, y and z axes.
  70502. * @param x The amount to scale the bone on the x axis.
  70503. * @param x The amount to scale the bone on the y axis.
  70504. * @param z The amount to scale the bone on the z axis.
  70505. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70506. */
  70507. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70508. if (scaleChildren === void 0) { scaleChildren = false; }
  70509. var locMat = this.getLocalMatrix();
  70510. var origLocMat = Bone._tmpMats[0];
  70511. origLocMat.copyFrom(locMat);
  70512. var origLocMatInv = Bone._tmpMats[1];
  70513. origLocMatInv.copyFrom(origLocMat);
  70514. origLocMatInv.invert();
  70515. var scaleMat = Bone._tmpMats[2];
  70516. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70517. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70518. this._scaleVector.x *= x;
  70519. this._scaleVector.y *= y;
  70520. this._scaleVector.z *= z;
  70521. locMat.multiplyToRef(origLocMatInv, locMat);
  70522. locMat.multiplyToRef(scaleMat, locMat);
  70523. locMat.multiplyToRef(origLocMat, locMat);
  70524. var parent = this.getParent();
  70525. if (parent) {
  70526. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70527. }
  70528. else {
  70529. this.getAbsoluteTransform().copyFrom(locMat);
  70530. }
  70531. var len = this.children.length;
  70532. scaleMat.invert();
  70533. for (var i = 0; i < len; i++) {
  70534. var child = this.children[i];
  70535. var cm = child.getLocalMatrix();
  70536. cm.multiplyToRef(scaleMat, cm);
  70537. var lm = child.getLocalMatrix();
  70538. lm.m[12] *= x;
  70539. lm.m[13] *= y;
  70540. lm.m[14] *= z;
  70541. }
  70542. this.computeAbsoluteTransforms();
  70543. if (scaleChildren) {
  70544. for (var i = 0; i < len; i++) {
  70545. this.children[i].scale(x, y, z, scaleChildren);
  70546. }
  70547. }
  70548. this.markAsDirty();
  70549. };
  70550. /**
  70551. * Set the yaw, pitch, and roll of the bone in local or world space.
  70552. * @param yaw The rotation of the bone on the y axis.
  70553. * @param pitch The rotation of the bone on the x axis.
  70554. * @param roll The rotation of the bone on the z axis.
  70555. * @param space The space that the axes of rotation are in.
  70556. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70557. */
  70558. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70559. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70560. var rotMat = Bone._tmpMats[0];
  70561. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70562. var rotMatInv = Bone._tmpMats[1];
  70563. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70564. rotMatInv.multiplyToRef(rotMat, rotMat);
  70565. this._rotateWithMatrix(rotMat, space, mesh);
  70566. };
  70567. /**
  70568. * Rotate the bone on an axis in local or world space.
  70569. * @param axis The axis to rotate the bone on.
  70570. * @param amount The amount to rotate the bone.
  70571. * @param space The space that the axis is in.
  70572. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70573. */
  70574. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70575. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70576. var rmat = Bone._tmpMats[0];
  70577. rmat.m[12] = 0;
  70578. rmat.m[13] = 0;
  70579. rmat.m[14] = 0;
  70580. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70581. this._rotateWithMatrix(rmat, space, mesh);
  70582. };
  70583. /**
  70584. * Set the rotation of the bone to a particular axis angle in local or world space.
  70585. * @param axis The axis to rotate the bone on.
  70586. * @param angle The angle that the bone should be rotated to.
  70587. * @param space The space that the axis is in.
  70588. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70589. */
  70590. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70592. var rotMat = Bone._tmpMats[0];
  70593. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70594. var rotMatInv = Bone._tmpMats[1];
  70595. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70596. rotMatInv.multiplyToRef(rotMat, rotMat);
  70597. this._rotateWithMatrix(rotMat, space, mesh);
  70598. };
  70599. /**
  70600. * Set the euler rotation of the bone in local of world space.
  70601. * @param rotation The euler rotation that the bone should be set to.
  70602. * @param space The space that the rotation is in.
  70603. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70604. */
  70605. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70606. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70607. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70608. };
  70609. /**
  70610. * Set the quaternion rotation of the bone in local of world space.
  70611. * @param quat The quaternion rotation that the bone should be set to.
  70612. * @param space The space that the rotation is in.
  70613. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70614. */
  70615. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70616. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70617. var rotMatInv = Bone._tmpMats[0];
  70618. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70619. var rotMat = Bone._tmpMats[1];
  70620. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70621. rotMatInv.multiplyToRef(rotMat, rotMat);
  70622. this._rotateWithMatrix(rotMat, space, mesh);
  70623. };
  70624. /**
  70625. * Set the rotation matrix of the bone in local of world space.
  70626. * @param rotMat The rotation matrix that the bone should be set to.
  70627. * @param space The space that the rotation is in.
  70628. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70629. */
  70630. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70631. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70632. var rotMatInv = Bone._tmpMats[0];
  70633. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70634. var rotMat2 = Bone._tmpMats[1];
  70635. rotMat2.copyFrom(rotMat);
  70636. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70637. this._rotateWithMatrix(rotMat2, space, mesh);
  70638. };
  70639. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70641. var lmat = this.getLocalMatrix();
  70642. var lx = lmat.m[12];
  70643. var ly = lmat.m[13];
  70644. var lz = lmat.m[14];
  70645. var parent = this.getParent();
  70646. var parentScale = Bone._tmpMats[3];
  70647. var parentScaleInv = Bone._tmpMats[4];
  70648. if (parent) {
  70649. if (space == BABYLON.Space.WORLD) {
  70650. if (mesh) {
  70651. parentScale.copyFrom(mesh.getWorldMatrix());
  70652. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70653. }
  70654. else {
  70655. parentScale.copyFrom(parent.getAbsoluteTransform());
  70656. }
  70657. }
  70658. else {
  70659. parentScale = parent._scaleMatrix;
  70660. }
  70661. parentScaleInv.copyFrom(parentScale);
  70662. parentScaleInv.invert();
  70663. lmat.multiplyToRef(parentScale, lmat);
  70664. lmat.multiplyToRef(rmat, lmat);
  70665. lmat.multiplyToRef(parentScaleInv, lmat);
  70666. }
  70667. else {
  70668. if (space == BABYLON.Space.WORLD && mesh) {
  70669. parentScale.copyFrom(mesh.getWorldMatrix());
  70670. parentScaleInv.copyFrom(parentScale);
  70671. parentScaleInv.invert();
  70672. lmat.multiplyToRef(parentScale, lmat);
  70673. lmat.multiplyToRef(rmat, lmat);
  70674. lmat.multiplyToRef(parentScaleInv, lmat);
  70675. }
  70676. else {
  70677. lmat.multiplyToRef(rmat, lmat);
  70678. }
  70679. }
  70680. lmat.m[12] = lx;
  70681. lmat.m[13] = ly;
  70682. lmat.m[14] = lz;
  70683. this.computeAbsoluteTransforms();
  70684. this.markAsDirty();
  70685. };
  70686. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70687. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70688. if (space == BABYLON.Space.WORLD) {
  70689. var scaleMatrix = Bone._tmpMats[2];
  70690. scaleMatrix.copyFrom(this._scaleMatrix);
  70691. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70692. if (mesh) {
  70693. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70694. var meshScale = Bone._tmpMats[3];
  70695. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70696. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70697. }
  70698. rotMatInv.invert();
  70699. scaleMatrix.m[0] *= this._scalingDeterminant;
  70700. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70701. }
  70702. else {
  70703. rotMatInv.copyFrom(this.getLocalMatrix());
  70704. rotMatInv.invert();
  70705. var scaleMatrix = Bone._tmpMats[2];
  70706. scaleMatrix.copyFrom(this._scaleMatrix);
  70707. if (this._parent) {
  70708. var pscaleMatrix = Bone._tmpMats[3];
  70709. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70710. pscaleMatrix.invert();
  70711. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70712. }
  70713. else {
  70714. scaleMatrix.m[0] *= this._scalingDeterminant;
  70715. }
  70716. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70717. }
  70718. };
  70719. /**
  70720. * Get the scale of the bone
  70721. * @returns the scale of the bone
  70722. */
  70723. Bone.prototype.getScale = function () {
  70724. return this._scaleVector.clone();
  70725. };
  70726. /**
  70727. * Copy the scale of the bone to a vector3.
  70728. * @param result The vector3 to copy the scale to
  70729. */
  70730. Bone.prototype.getScaleToRef = function (result) {
  70731. result.copyFrom(this._scaleVector);
  70732. };
  70733. /**
  70734. * Get the position of the bone in local or world space.
  70735. * @param space The space that the returned position is in.
  70736. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70737. * @returns The position of the bone
  70738. */
  70739. Bone.prototype.getPosition = function (space, mesh) {
  70740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70741. if (mesh === void 0) { mesh = null; }
  70742. var pos = BABYLON.Vector3.Zero();
  70743. this.getPositionToRef(space, mesh, pos);
  70744. return pos;
  70745. };
  70746. /**
  70747. * Copy the position of the bone to a vector3 in local or world space.
  70748. * @param space The space that the returned position is in.
  70749. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70750. * @param result The vector3 to copy the position to.
  70751. */
  70752. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70753. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70754. if (space == BABYLON.Space.LOCAL) {
  70755. var lm = this.getLocalMatrix();
  70756. result.x = lm.m[12];
  70757. result.y = lm.m[13];
  70758. result.z = lm.m[14];
  70759. }
  70760. else {
  70761. var wm = null;
  70762. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70763. if (mesh) {
  70764. wm = mesh.getWorldMatrix();
  70765. }
  70766. this._skeleton.computeAbsoluteTransforms();
  70767. var tmat = Bone._tmpMats[0];
  70768. if (mesh && wm) {
  70769. tmat.copyFrom(this.getAbsoluteTransform());
  70770. tmat.multiplyToRef(wm, tmat);
  70771. }
  70772. else {
  70773. tmat = this.getAbsoluteTransform();
  70774. }
  70775. result.x = tmat.m[12];
  70776. result.y = tmat.m[13];
  70777. result.z = tmat.m[14];
  70778. }
  70779. };
  70780. /**
  70781. * Get the absolute position of the bone (world space).
  70782. * @param mesh The mesh that this bone is attached to.
  70783. * @returns The absolute position of the bone
  70784. */
  70785. Bone.prototype.getAbsolutePosition = function (mesh) {
  70786. if (mesh === void 0) { mesh = null; }
  70787. var pos = BABYLON.Vector3.Zero();
  70788. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70789. return pos;
  70790. };
  70791. /**
  70792. * Copy the absolute position of the bone (world space) to the result param.
  70793. * @param mesh The mesh that this bone is attached to.
  70794. * @param result The vector3 to copy the absolute position to.
  70795. */
  70796. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70797. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70798. };
  70799. /**
  70800. * Compute the absolute transforms of this bone and its children.
  70801. */
  70802. Bone.prototype.computeAbsoluteTransforms = function () {
  70803. if (this._parent) {
  70804. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70805. }
  70806. else {
  70807. this._absoluteTransform.copyFrom(this._localMatrix);
  70808. var poseMatrix = this._skeleton.getPoseMatrix();
  70809. if (poseMatrix) {
  70810. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70811. }
  70812. }
  70813. var children = this.children;
  70814. var len = children.length;
  70815. for (var i = 0; i < len; i++) {
  70816. children[i].computeAbsoluteTransforms();
  70817. }
  70818. };
  70819. Bone.prototype._syncScaleVector = function () {
  70820. var lm = this.getLocalMatrix();
  70821. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70822. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70823. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70824. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70825. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70826. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70827. this._scaleVector.x = xs * Math.sqrt(xsq);
  70828. this._scaleVector.y = ys * Math.sqrt(ysq);
  70829. this._scaleVector.z = zs * Math.sqrt(zsq);
  70830. if (this._parent) {
  70831. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70832. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70833. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70834. }
  70835. 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);
  70836. };
  70837. /**
  70838. * Get the world direction from an axis that is in the local space of the bone.
  70839. * @param localAxis The local direction that is used to compute the world direction.
  70840. * @param mesh The mesh that this bone is attached to.
  70841. * @returns The world direction
  70842. */
  70843. Bone.prototype.getDirection = function (localAxis, mesh) {
  70844. if (mesh === void 0) { mesh = null; }
  70845. var result = BABYLON.Vector3.Zero();
  70846. this.getDirectionToRef(localAxis, mesh, result);
  70847. return result;
  70848. };
  70849. /**
  70850. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70851. * @param localAxis The local direction that is used to compute the world direction.
  70852. * @param mesh The mesh that this bone is attached to.
  70853. * @param result The vector3 that the world direction will be copied to.
  70854. */
  70855. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70856. if (mesh === void 0) { mesh = null; }
  70857. var wm = null;
  70858. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70859. if (mesh) {
  70860. wm = mesh.getWorldMatrix();
  70861. }
  70862. this._skeleton.computeAbsoluteTransforms();
  70863. var mat = Bone._tmpMats[0];
  70864. mat.copyFrom(this.getAbsoluteTransform());
  70865. if (mesh && wm) {
  70866. mat.multiplyToRef(wm, mat);
  70867. }
  70868. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70869. result.normalize();
  70870. };
  70871. /**
  70872. * Get the euler rotation of the bone in local or world space.
  70873. * @param space The space that the rotation should be in.
  70874. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70875. * @returns The euler rotation
  70876. */
  70877. Bone.prototype.getRotation = function (space, mesh) {
  70878. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70879. if (mesh === void 0) { mesh = null; }
  70880. var result = BABYLON.Vector3.Zero();
  70881. this.getRotationToRef(space, mesh, result);
  70882. return result;
  70883. };
  70884. /**
  70885. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70886. * @param space The space that the rotation should be in.
  70887. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70888. * @param result The vector3 that the rotation should be copied to.
  70889. */
  70890. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70891. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70892. if (mesh === void 0) { mesh = null; }
  70893. var quat = Bone._tmpQuat;
  70894. this.getRotationQuaternionToRef(space, mesh, quat);
  70895. quat.toEulerAnglesToRef(result);
  70896. };
  70897. /**
  70898. * Get the quaternion rotation of the bone in either local or world space.
  70899. * @param space The space that the rotation should be in.
  70900. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70901. * @returns The quaternion rotation
  70902. */
  70903. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70904. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70905. if (mesh === void 0) { mesh = null; }
  70906. var result = BABYLON.Quaternion.Identity();
  70907. this.getRotationQuaternionToRef(space, mesh, result);
  70908. return result;
  70909. };
  70910. /**
  70911. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70912. * @param space The space that the rotation should be in.
  70913. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70914. * @param result The quaternion that the rotation should be copied to.
  70915. */
  70916. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70918. if (mesh === void 0) { mesh = null; }
  70919. if (space == BABYLON.Space.LOCAL) {
  70920. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70921. }
  70922. else {
  70923. var mat = Bone._tmpMats[0];
  70924. var amat = this.getAbsoluteTransform();
  70925. if (mesh) {
  70926. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70927. }
  70928. else {
  70929. mat.copyFrom(amat);
  70930. }
  70931. mat.m[0] *= this._scalingDeterminant;
  70932. mat.m[1] *= this._scalingDeterminant;
  70933. mat.m[2] *= this._scalingDeterminant;
  70934. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70935. }
  70936. };
  70937. /**
  70938. * Get the rotation matrix of the bone in local or world space.
  70939. * @param space The space that the rotation should be in.
  70940. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70941. * @returns The rotation matrix
  70942. */
  70943. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70944. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70945. var result = BABYLON.Matrix.Identity();
  70946. this.getRotationMatrixToRef(space, mesh, result);
  70947. return result;
  70948. };
  70949. /**
  70950. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70951. * @param space The space that the rotation should be in.
  70952. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70953. * @param result The quaternion that the rotation should be copied to.
  70954. */
  70955. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70956. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70957. if (space == BABYLON.Space.LOCAL) {
  70958. this.getLocalMatrix().getRotationMatrixToRef(result);
  70959. }
  70960. else {
  70961. var mat = Bone._tmpMats[0];
  70962. var amat = this.getAbsoluteTransform();
  70963. if (mesh) {
  70964. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70965. }
  70966. else {
  70967. mat.copyFrom(amat);
  70968. }
  70969. mat.m[0] *= this._scalingDeterminant;
  70970. mat.m[1] *= this._scalingDeterminant;
  70971. mat.m[2] *= this._scalingDeterminant;
  70972. mat.getRotationMatrixToRef(result);
  70973. }
  70974. };
  70975. /**
  70976. * Get the world position of a point that is in the local space of the bone.
  70977. * @param position The local position
  70978. * @param mesh The mesh that this bone is attached to.
  70979. * @returns The world position
  70980. */
  70981. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70982. if (mesh === void 0) { mesh = null; }
  70983. var result = BABYLON.Vector3.Zero();
  70984. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70985. return result;
  70986. };
  70987. /**
  70988. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70989. * @param position The local position
  70990. * @param mesh The mesh that this bone is attached to.
  70991. * @param result The vector3 that the world position should be copied to.
  70992. */
  70993. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70994. if (mesh === void 0) { mesh = null; }
  70995. var wm = null;
  70996. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70997. if (mesh) {
  70998. wm = mesh.getWorldMatrix();
  70999. }
  71000. this._skeleton.computeAbsoluteTransforms();
  71001. var tmat = Bone._tmpMats[0];
  71002. if (mesh && wm) {
  71003. tmat.copyFrom(this.getAbsoluteTransform());
  71004. tmat.multiplyToRef(wm, tmat);
  71005. }
  71006. else {
  71007. tmat = this.getAbsoluteTransform();
  71008. }
  71009. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71010. };
  71011. /**
  71012. * Get the local position of a point that is in world space.
  71013. * @param position The world position
  71014. * @param mesh The mesh that this bone is attached to.
  71015. * @returns The local position
  71016. */
  71017. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71018. if (mesh === void 0) { mesh = null; }
  71019. var result = BABYLON.Vector3.Zero();
  71020. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71021. return result;
  71022. };
  71023. /**
  71024. * Get the local position of a point that is in world space and copy it to the result param.
  71025. * @param position The world position
  71026. * @param mesh The mesh that this bone is attached to.
  71027. * @param result The vector3 that the local position should be copied to.
  71028. */
  71029. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71030. if (mesh === void 0) { mesh = null; }
  71031. var wm = null;
  71032. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71033. if (mesh) {
  71034. wm = mesh.getWorldMatrix();
  71035. }
  71036. this._skeleton.computeAbsoluteTransforms();
  71037. var tmat = Bone._tmpMats[0];
  71038. tmat.copyFrom(this.getAbsoluteTransform());
  71039. if (mesh && wm) {
  71040. tmat.multiplyToRef(wm, tmat);
  71041. }
  71042. tmat.invert();
  71043. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71044. };
  71045. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71046. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71047. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71048. return Bone;
  71049. }(BABYLON.Node));
  71050. BABYLON.Bone = Bone;
  71051. })(BABYLON || (BABYLON = {}));
  71052. //# sourceMappingURL=babylon.bone.js.map
  71053. var BABYLON;
  71054. (function (BABYLON) {
  71055. var BoneIKController = /** @class */ (function () {
  71056. function BoneIKController(mesh, bone, options) {
  71057. this.targetPosition = BABYLON.Vector3.Zero();
  71058. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71059. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71060. this.poleAngle = 0;
  71061. this.slerpAmount = 1;
  71062. this._bone1Quat = BABYLON.Quaternion.Identity();
  71063. this._bone1Mat = BABYLON.Matrix.Identity();
  71064. this._bone2Ang = Math.PI;
  71065. this._maxAngle = Math.PI;
  71066. this._rightHandedSystem = false;
  71067. this._bendAxis = BABYLON.Vector3.Right();
  71068. this._slerping = false;
  71069. this._adjustRoll = 0;
  71070. this._bone2 = bone;
  71071. this._bone1 = bone.getParent();
  71072. if (!this._bone1) {
  71073. return;
  71074. }
  71075. this.mesh = mesh;
  71076. var bonePos = bone.getPosition();
  71077. if (bone.getAbsoluteTransform().determinant() > 0) {
  71078. this._rightHandedSystem = true;
  71079. this._bendAxis.x = 0;
  71080. this._bendAxis.y = 0;
  71081. this._bendAxis.z = -1;
  71082. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71083. this._adjustRoll = Math.PI * .5;
  71084. this._bendAxis.z = 1;
  71085. }
  71086. }
  71087. if (this._bone1.length) {
  71088. var boneScale1 = this._bone1.getScale();
  71089. var boneScale2 = this._bone2.getScale();
  71090. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71091. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71092. }
  71093. else if (this._bone1.children[0]) {
  71094. mesh.computeWorldMatrix(true);
  71095. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71096. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71097. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71098. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71099. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71100. }
  71101. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71102. this.maxAngle = Math.PI;
  71103. if (options) {
  71104. if (options.targetMesh) {
  71105. this.targetMesh = options.targetMesh;
  71106. this.targetMesh.computeWorldMatrix(true);
  71107. }
  71108. if (options.poleTargetMesh) {
  71109. this.poleTargetMesh = options.poleTargetMesh;
  71110. this.poleTargetMesh.computeWorldMatrix(true);
  71111. }
  71112. else if (options.poleTargetBone) {
  71113. this.poleTargetBone = options.poleTargetBone;
  71114. }
  71115. else if (this._bone1.getParent()) {
  71116. this.poleTargetBone = this._bone1.getParent();
  71117. }
  71118. if (options.poleTargetLocalOffset) {
  71119. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71120. }
  71121. if (options.poleAngle) {
  71122. this.poleAngle = options.poleAngle;
  71123. }
  71124. if (options.bendAxis) {
  71125. this._bendAxis.copyFrom(options.bendAxis);
  71126. }
  71127. if (options.maxAngle) {
  71128. this.maxAngle = options.maxAngle;
  71129. }
  71130. if (options.slerpAmount) {
  71131. this.slerpAmount = options.slerpAmount;
  71132. }
  71133. }
  71134. }
  71135. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71136. get: function () {
  71137. return this._maxAngle;
  71138. },
  71139. set: function (value) {
  71140. this._setMaxAngle(value);
  71141. },
  71142. enumerable: true,
  71143. configurable: true
  71144. });
  71145. BoneIKController.prototype._setMaxAngle = function (ang) {
  71146. if (ang < 0) {
  71147. ang = 0;
  71148. }
  71149. if (ang > Math.PI || ang == undefined) {
  71150. ang = Math.PI;
  71151. }
  71152. this._maxAngle = ang;
  71153. var a = this._bone1Length;
  71154. var b = this._bone2Length;
  71155. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71156. };
  71157. BoneIKController.prototype.update = function () {
  71158. var bone1 = this._bone1;
  71159. if (!bone1) {
  71160. return;
  71161. }
  71162. var target = this.targetPosition;
  71163. var poleTarget = this.poleTargetPosition;
  71164. var mat1 = BoneIKController._tmpMats[0];
  71165. var mat2 = BoneIKController._tmpMats[1];
  71166. if (this.targetMesh) {
  71167. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71168. }
  71169. if (this.poleTargetBone) {
  71170. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71171. }
  71172. else if (this.poleTargetMesh) {
  71173. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71174. }
  71175. var bonePos = BoneIKController._tmpVecs[0];
  71176. var zaxis = BoneIKController._tmpVecs[1];
  71177. var xaxis = BoneIKController._tmpVecs[2];
  71178. var yaxis = BoneIKController._tmpVecs[3];
  71179. var upAxis = BoneIKController._tmpVecs[4];
  71180. var _tmpQuat = BoneIKController._tmpQuat;
  71181. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71182. poleTarget.subtractToRef(bonePos, upAxis);
  71183. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71184. upAxis.y = 1;
  71185. }
  71186. else {
  71187. upAxis.normalize();
  71188. }
  71189. target.subtractToRef(bonePos, yaxis);
  71190. yaxis.normalize();
  71191. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71192. zaxis.normalize();
  71193. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71194. xaxis.normalize();
  71195. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71196. var a = this._bone1Length;
  71197. var b = this._bone2Length;
  71198. var c = BABYLON.Vector3.Distance(bonePos, target);
  71199. if (this._maxReach > 0) {
  71200. c = Math.min(this._maxReach, c);
  71201. }
  71202. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71203. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71204. if (acosa > 1) {
  71205. acosa = 1;
  71206. }
  71207. if (acosb > 1) {
  71208. acosb = 1;
  71209. }
  71210. if (acosa < -1) {
  71211. acosa = -1;
  71212. }
  71213. if (acosb < -1) {
  71214. acosb = -1;
  71215. }
  71216. var angA = Math.acos(acosa);
  71217. var angB = Math.acos(acosb);
  71218. var angC = -angA - angB;
  71219. if (this._rightHandedSystem) {
  71220. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71221. mat2.multiplyToRef(mat1, mat1);
  71222. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71223. mat2.multiplyToRef(mat1, mat1);
  71224. }
  71225. else {
  71226. var _tmpVec = BoneIKController._tmpVecs[5];
  71227. _tmpVec.copyFrom(this._bendAxis);
  71228. _tmpVec.x *= -1;
  71229. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71230. mat2.multiplyToRef(mat1, mat1);
  71231. }
  71232. if (this.poleAngle) {
  71233. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71234. mat1.multiplyToRef(mat2, mat1);
  71235. }
  71236. if (this._bone1) {
  71237. if (this.slerpAmount < 1) {
  71238. if (!this._slerping) {
  71239. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71240. }
  71241. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71242. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71243. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71244. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71245. this._slerping = true;
  71246. }
  71247. else {
  71248. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71249. this._bone1Mat.copyFrom(mat1);
  71250. this._slerping = false;
  71251. }
  71252. }
  71253. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71254. this._bone2Ang = angC;
  71255. };
  71256. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71257. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71258. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71259. return BoneIKController;
  71260. }());
  71261. BABYLON.BoneIKController = BoneIKController;
  71262. })(BABYLON || (BABYLON = {}));
  71263. //# sourceMappingURL=babylon.boneIKController.js.map
  71264. var BABYLON;
  71265. (function (BABYLON) {
  71266. var BoneLookController = /** @class */ (function () {
  71267. /**
  71268. * Create a BoneLookController
  71269. * @param mesh the mesh that the bone belongs to
  71270. * @param bone the bone that will be looking to the target
  71271. * @param target the target Vector3 to look at
  71272. * @param settings optional settings:
  71273. * - maxYaw: the maximum angle the bone will yaw to
  71274. * - minYaw: the minimum angle the bone will yaw to
  71275. * - maxPitch: the maximum angle the bone will pitch to
  71276. * - minPitch: the minimum angle the bone will yaw to
  71277. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71278. * - upAxis: the up axis of the coordinate system
  71279. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71280. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71281. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71282. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71283. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71284. * - adjustRoll: used to make an adjustment to the roll of the bone
  71285. **/
  71286. function BoneLookController(mesh, bone, target, options) {
  71287. /**
  71288. * The up axis of the coordinate system that is used when the bone is rotated.
  71289. */
  71290. this.upAxis = BABYLON.Vector3.Up();
  71291. /**
  71292. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71293. */
  71294. this.upAxisSpace = BABYLON.Space.LOCAL;
  71295. /**
  71296. * Used to make an adjustment to the yaw of the bone.
  71297. */
  71298. this.adjustYaw = 0;
  71299. /**
  71300. * Used to make an adjustment to the pitch of the bone.
  71301. */
  71302. this.adjustPitch = 0;
  71303. /**
  71304. * Used to make an adjustment to the roll of the bone.
  71305. */
  71306. this.adjustRoll = 0;
  71307. /**
  71308. * 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).
  71309. */
  71310. this.slerpAmount = 1;
  71311. this._boneQuat = BABYLON.Quaternion.Identity();
  71312. this._slerping = false;
  71313. this._firstFrameSkipped = false;
  71314. this._fowardAxis = BABYLON.Vector3.Forward();
  71315. this.mesh = mesh;
  71316. this.bone = bone;
  71317. this.target = target;
  71318. if (options) {
  71319. if (options.adjustYaw) {
  71320. this.adjustYaw = options.adjustYaw;
  71321. }
  71322. if (options.adjustPitch) {
  71323. this.adjustPitch = options.adjustPitch;
  71324. }
  71325. if (options.adjustRoll) {
  71326. this.adjustRoll = options.adjustRoll;
  71327. }
  71328. if (options.maxYaw != null) {
  71329. this.maxYaw = options.maxYaw;
  71330. }
  71331. else {
  71332. this.maxYaw = Math.PI;
  71333. }
  71334. if (options.minYaw != null) {
  71335. this.minYaw = options.minYaw;
  71336. }
  71337. else {
  71338. this.minYaw = -Math.PI;
  71339. }
  71340. if (options.maxPitch != null) {
  71341. this.maxPitch = options.maxPitch;
  71342. }
  71343. else {
  71344. this.maxPitch = Math.PI;
  71345. }
  71346. if (options.minPitch != null) {
  71347. this.minPitch = options.minPitch;
  71348. }
  71349. else {
  71350. this.minPitch = -Math.PI;
  71351. }
  71352. if (options.slerpAmount != null) {
  71353. this.slerpAmount = options.slerpAmount;
  71354. }
  71355. if (options.upAxis != null) {
  71356. this.upAxis = options.upAxis;
  71357. }
  71358. if (options.upAxisSpace != null) {
  71359. this.upAxisSpace = options.upAxisSpace;
  71360. }
  71361. if (options.yawAxis != null || options.pitchAxis != null) {
  71362. var newYawAxis = BABYLON.Axis.Y;
  71363. var newPitchAxis = BABYLON.Axis.X;
  71364. if (options.yawAxis != null) {
  71365. newYawAxis = options.yawAxis.clone();
  71366. newYawAxis.normalize();
  71367. }
  71368. if (options.pitchAxis != null) {
  71369. newPitchAxis = options.pitchAxis.clone();
  71370. newPitchAxis.normalize();
  71371. }
  71372. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71373. this._transformYawPitch = BABYLON.Matrix.Identity();
  71374. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71375. this._transformYawPitchInv = this._transformYawPitch.clone();
  71376. this._transformYawPitch.invert();
  71377. }
  71378. }
  71379. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71380. this.upAxisSpace = BABYLON.Space.LOCAL;
  71381. }
  71382. }
  71383. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71384. /**
  71385. * Get/set the minimum yaw angle that the bone can look to.
  71386. */
  71387. get: function () {
  71388. return this._minYaw;
  71389. },
  71390. set: function (value) {
  71391. this._minYaw = value;
  71392. this._minYawSin = Math.sin(value);
  71393. this._minYawCos = Math.cos(value);
  71394. if (this._maxYaw != null) {
  71395. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71396. this._yawRange = this._maxYaw - this._minYaw;
  71397. }
  71398. },
  71399. enumerable: true,
  71400. configurable: true
  71401. });
  71402. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71403. /**
  71404. * Get/set the maximum yaw angle that the bone can look to.
  71405. */
  71406. get: function () {
  71407. return this._maxYaw;
  71408. },
  71409. set: function (value) {
  71410. this._maxYaw = value;
  71411. this._maxYawSin = Math.sin(value);
  71412. this._maxYawCos = Math.cos(value);
  71413. if (this._minYaw != null) {
  71414. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71415. this._yawRange = this._maxYaw - this._minYaw;
  71416. }
  71417. },
  71418. enumerable: true,
  71419. configurable: true
  71420. });
  71421. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71422. /**
  71423. * Get/set the minimum pitch angle that the bone can look to.
  71424. */
  71425. get: function () {
  71426. return this._minPitch;
  71427. },
  71428. set: function (value) {
  71429. this._minPitch = value;
  71430. this._minPitchTan = Math.tan(value);
  71431. },
  71432. enumerable: true,
  71433. configurable: true
  71434. });
  71435. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71436. /**
  71437. * Get/set the maximum pitch angle that the bone can look to.
  71438. */
  71439. get: function () {
  71440. return this._maxPitch;
  71441. },
  71442. set: function (value) {
  71443. this._maxPitch = value;
  71444. this._maxPitchTan = Math.tan(value);
  71445. },
  71446. enumerable: true,
  71447. configurable: true
  71448. });
  71449. /**
  71450. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71451. */
  71452. BoneLookController.prototype.update = function () {
  71453. //skip the first frame when slerping so that the mesh rotation is correct
  71454. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71455. this._firstFrameSkipped = true;
  71456. return;
  71457. }
  71458. var bone = this.bone;
  71459. var bonePos = BoneLookController._tmpVecs[0];
  71460. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71461. var target = this.target;
  71462. var _tmpMat1 = BoneLookController._tmpMats[0];
  71463. var _tmpMat2 = BoneLookController._tmpMats[1];
  71464. var mesh = this.mesh;
  71465. var parentBone = bone.getParent();
  71466. var upAxis = BoneLookController._tmpVecs[1];
  71467. upAxis.copyFrom(this.upAxis);
  71468. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71469. if (this._transformYawPitch) {
  71470. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71471. }
  71472. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71473. }
  71474. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71475. mesh.getDirectionToRef(upAxis, upAxis);
  71476. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71477. upAxis.normalize();
  71478. }
  71479. }
  71480. var checkYaw = false;
  71481. var checkPitch = false;
  71482. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71483. checkYaw = true;
  71484. }
  71485. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71486. checkPitch = true;
  71487. }
  71488. if (checkYaw || checkPitch) {
  71489. var spaceMat = BoneLookController._tmpMats[2];
  71490. var spaceMatInv = BoneLookController._tmpMats[3];
  71491. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71492. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71493. }
  71494. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71495. spaceMat.copyFrom(mesh.getWorldMatrix());
  71496. }
  71497. else {
  71498. var forwardAxis = BoneLookController._tmpVecs[2];
  71499. forwardAxis.copyFrom(this._fowardAxis);
  71500. if (this._transformYawPitch) {
  71501. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71502. }
  71503. if (parentBone) {
  71504. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71505. }
  71506. else {
  71507. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71508. }
  71509. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71510. rightAxis.normalize();
  71511. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71512. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71513. }
  71514. spaceMat.invertToRef(spaceMatInv);
  71515. var xzlen = null;
  71516. if (checkPitch) {
  71517. var localTarget = BoneLookController._tmpVecs[3];
  71518. target.subtractToRef(bonePos, localTarget);
  71519. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71520. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71521. var pitch = Math.atan2(localTarget.y, xzlen);
  71522. var newPitch = pitch;
  71523. if (pitch > this._maxPitch) {
  71524. localTarget.y = this._maxPitchTan * xzlen;
  71525. newPitch = this._maxPitch;
  71526. }
  71527. else if (pitch < this._minPitch) {
  71528. localTarget.y = this._minPitchTan * xzlen;
  71529. newPitch = this._minPitch;
  71530. }
  71531. if (pitch != newPitch) {
  71532. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71533. localTarget.addInPlace(bonePos);
  71534. target = localTarget;
  71535. }
  71536. }
  71537. if (checkYaw) {
  71538. var localTarget = BoneLookController._tmpVecs[4];
  71539. target.subtractToRef(bonePos, localTarget);
  71540. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71541. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71542. var newYaw = yaw;
  71543. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71544. if (xzlen == null) {
  71545. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71546. }
  71547. if (this._yawRange > Math.PI) {
  71548. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71549. localTarget.z = this._maxYawCos * xzlen;
  71550. localTarget.x = this._maxYawSin * xzlen;
  71551. newYaw = this._maxYaw;
  71552. }
  71553. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71554. localTarget.z = this._minYawCos * xzlen;
  71555. localTarget.x = this._minYawSin * xzlen;
  71556. newYaw = this._minYaw;
  71557. }
  71558. }
  71559. else {
  71560. if (yaw > this._maxYaw) {
  71561. localTarget.z = this._maxYawCos * xzlen;
  71562. localTarget.x = this._maxYawSin * xzlen;
  71563. newYaw = this._maxYaw;
  71564. }
  71565. else if (yaw < this._minYaw) {
  71566. localTarget.z = this._minYawCos * xzlen;
  71567. localTarget.x = this._minYawSin * xzlen;
  71568. newYaw = this._minYaw;
  71569. }
  71570. }
  71571. }
  71572. if (this._slerping && this._yawRange > Math.PI) {
  71573. //are we going to be crossing into the min/max region?
  71574. var boneFwd = BoneLookController._tmpVecs[8];
  71575. boneFwd.copyFrom(BABYLON.Axis.Z);
  71576. if (this._transformYawPitch) {
  71577. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71578. }
  71579. var boneRotMat = BoneLookController._tmpMats[4];
  71580. this._boneQuat.toRotationMatrix(boneRotMat);
  71581. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71582. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71583. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71584. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71585. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71586. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71587. if (angBtwTar > angBtwMidYaw) {
  71588. if (xzlen == null) {
  71589. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71590. }
  71591. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71592. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71593. if (angBtwMin < angBtwMax) {
  71594. newYaw = boneYaw + Math.PI * .75;
  71595. localTarget.z = Math.cos(newYaw) * xzlen;
  71596. localTarget.x = Math.sin(newYaw) * xzlen;
  71597. }
  71598. else {
  71599. newYaw = boneYaw - Math.PI * .75;
  71600. localTarget.z = Math.cos(newYaw) * xzlen;
  71601. localTarget.x = Math.sin(newYaw) * xzlen;
  71602. }
  71603. }
  71604. }
  71605. if (yaw != newYaw) {
  71606. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71607. localTarget.addInPlace(bonePos);
  71608. target = localTarget;
  71609. }
  71610. }
  71611. }
  71612. var zaxis = BoneLookController._tmpVecs[5];
  71613. var xaxis = BoneLookController._tmpVecs[6];
  71614. var yaxis = BoneLookController._tmpVecs[7];
  71615. var _tmpQuat = BoneLookController._tmpQuat;
  71616. target.subtractToRef(bonePos, zaxis);
  71617. zaxis.normalize();
  71618. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71619. xaxis.normalize();
  71620. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71621. yaxis.normalize();
  71622. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71623. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71624. return;
  71625. }
  71626. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71627. return;
  71628. }
  71629. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71630. return;
  71631. }
  71632. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71633. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71634. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71635. }
  71636. if (this.slerpAmount < 1) {
  71637. if (!this._slerping) {
  71638. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71639. }
  71640. if (this._transformYawPitch) {
  71641. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71642. }
  71643. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71644. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71645. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71646. this._slerping = true;
  71647. }
  71648. else {
  71649. if (this._transformYawPitch) {
  71650. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71651. }
  71652. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71653. this._slerping = false;
  71654. }
  71655. };
  71656. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71657. var angDiff = ang2 - ang1;
  71658. angDiff %= Math.PI * 2;
  71659. if (angDiff > Math.PI) {
  71660. angDiff -= Math.PI * 2;
  71661. }
  71662. else if (angDiff < -Math.PI) {
  71663. angDiff += Math.PI * 2;
  71664. }
  71665. return angDiff;
  71666. };
  71667. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71668. ang1 %= (2 * Math.PI);
  71669. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71670. ang2 %= (2 * Math.PI);
  71671. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71672. var ab = 0;
  71673. if (ang1 < ang2) {
  71674. ab = ang2 - ang1;
  71675. }
  71676. else {
  71677. ab = ang1 - ang2;
  71678. }
  71679. if (ab > Math.PI) {
  71680. ab = Math.PI * 2 - ab;
  71681. }
  71682. return ab;
  71683. };
  71684. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71685. ang %= (2 * Math.PI);
  71686. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71687. ang1 %= (2 * Math.PI);
  71688. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71689. ang2 %= (2 * Math.PI);
  71690. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71691. if (ang1 < ang2) {
  71692. if (ang > ang1 && ang < ang2) {
  71693. return true;
  71694. }
  71695. }
  71696. else {
  71697. if (ang > ang2 && ang < ang1) {
  71698. return true;
  71699. }
  71700. }
  71701. return false;
  71702. };
  71703. 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()];
  71704. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71705. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71706. return BoneLookController;
  71707. }());
  71708. BABYLON.BoneLookController = BoneLookController;
  71709. })(BABYLON || (BABYLON = {}));
  71710. //# sourceMappingURL=babylon.boneLookController.js.map
  71711. var BABYLON;
  71712. (function (BABYLON) {
  71713. var Skeleton = /** @class */ (function () {
  71714. function Skeleton(name, id, scene) {
  71715. this.name = name;
  71716. this.id = id;
  71717. this.bones = new Array();
  71718. this.needInitialSkinMatrix = false;
  71719. this._isDirty = true;
  71720. this._meshesWithPoseMatrix = new Array();
  71721. this._identity = BABYLON.Matrix.Identity();
  71722. this._ranges = {};
  71723. this._lastAbsoluteTransformsUpdateId = -1;
  71724. /**
  71725. * Specifies if the skeleton should be serialized.
  71726. */
  71727. this.doNotSerialize = false;
  71728. // Events
  71729. /**
  71730. * An event triggered before computing the skeleton's matrices
  71731. * @type {BABYLON.Observable}
  71732. */
  71733. this.onBeforeComputeObservable = new BABYLON.Observable();
  71734. this.bones = [];
  71735. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71736. scene.skeletons.push(this);
  71737. //make sure it will recalculate the matrix next time prepare is called.
  71738. this._isDirty = true;
  71739. }
  71740. // Members
  71741. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71742. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71743. return mesh._bonesTransformMatrices;
  71744. }
  71745. if (!this._transformMatrices) {
  71746. this.prepare();
  71747. }
  71748. return this._transformMatrices;
  71749. };
  71750. Skeleton.prototype.getScene = function () {
  71751. return this._scene;
  71752. };
  71753. // Methods
  71754. /**
  71755. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71756. */
  71757. Skeleton.prototype.toString = function (fullDetails) {
  71758. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71759. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71760. if (fullDetails) {
  71761. ret += ", Ranges: {";
  71762. var first = true;
  71763. for (var name_1 in this._ranges) {
  71764. if (first) {
  71765. ret += ", ";
  71766. first = false;
  71767. }
  71768. ret += name_1;
  71769. }
  71770. ret += "}";
  71771. }
  71772. return ret;
  71773. };
  71774. /**
  71775. * Get bone's index searching by name
  71776. * @param {string} name is bone's name to search for
  71777. * @return {number} Indice of the bone. Returns -1 if not found
  71778. */
  71779. Skeleton.prototype.getBoneIndexByName = function (name) {
  71780. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71781. if (this.bones[boneIndex].name === name) {
  71782. return boneIndex;
  71783. }
  71784. }
  71785. return -1;
  71786. };
  71787. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71788. // check name not already in use
  71789. if (!this._ranges[name]) {
  71790. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71791. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71792. if (this.bones[i].animations[0]) {
  71793. this.bones[i].animations[0].createRange(name, from, to);
  71794. }
  71795. }
  71796. }
  71797. };
  71798. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71799. if (deleteFrames === void 0) { deleteFrames = true; }
  71800. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71801. if (this.bones[i].animations[0]) {
  71802. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71803. }
  71804. }
  71805. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71806. };
  71807. Skeleton.prototype.getAnimationRange = function (name) {
  71808. return this._ranges[name];
  71809. };
  71810. /**
  71811. * Returns as an Array, all AnimationRanges defined on this skeleton
  71812. */
  71813. Skeleton.prototype.getAnimationRanges = function () {
  71814. var animationRanges = [];
  71815. var name;
  71816. var i = 0;
  71817. for (name in this._ranges) {
  71818. animationRanges[i] = this._ranges[name];
  71819. i++;
  71820. }
  71821. return animationRanges;
  71822. };
  71823. /**
  71824. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71825. */
  71826. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71827. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71828. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71829. return false;
  71830. }
  71831. var ret = true;
  71832. var frameOffset = this._getHighestAnimationFrame() + 1;
  71833. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71834. var boneDict = {};
  71835. var sourceBones = source.bones;
  71836. var nBones;
  71837. var i;
  71838. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71839. boneDict[sourceBones[i].name] = sourceBones[i];
  71840. }
  71841. if (this.bones.length !== sourceBones.length) {
  71842. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71843. ret = false;
  71844. }
  71845. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71846. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71847. var boneName = this.bones[i].name;
  71848. var sourceBone = boneDict[boneName];
  71849. if (sourceBone) {
  71850. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71851. }
  71852. else {
  71853. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71854. ret = false;
  71855. }
  71856. }
  71857. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71858. var range = source.getAnimationRange(name);
  71859. if (range) {
  71860. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71861. }
  71862. return ret;
  71863. };
  71864. Skeleton.prototype.returnToRest = function () {
  71865. for (var index = 0; index < this.bones.length; index++) {
  71866. this.bones[index].returnToRest();
  71867. }
  71868. };
  71869. Skeleton.prototype._getHighestAnimationFrame = function () {
  71870. var ret = 0;
  71871. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71872. if (this.bones[i].animations[0]) {
  71873. var highest = this.bones[i].animations[0].getHighestFrame();
  71874. if (ret < highest) {
  71875. ret = highest;
  71876. }
  71877. }
  71878. }
  71879. return ret;
  71880. };
  71881. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71882. var range = this.getAnimationRange(name);
  71883. if (!range) {
  71884. return null;
  71885. }
  71886. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71887. };
  71888. Skeleton.prototype._markAsDirty = function () {
  71889. this._isDirty = true;
  71890. };
  71891. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71892. this._meshesWithPoseMatrix.push(mesh);
  71893. };
  71894. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71895. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71896. if (index > -1) {
  71897. this._meshesWithPoseMatrix.splice(index, 1);
  71898. }
  71899. };
  71900. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71901. this.onBeforeComputeObservable.notifyObservers(this);
  71902. for (var index = 0; index < this.bones.length; index++) {
  71903. var bone = this.bones[index];
  71904. var parentBone = bone.getParent();
  71905. if (parentBone) {
  71906. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71907. }
  71908. else {
  71909. if (initialSkinMatrix) {
  71910. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71911. }
  71912. else {
  71913. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71914. }
  71915. }
  71916. if (bone._index !== -1) {
  71917. var mappedIndex = bone._index === null ? index : bone._index;
  71918. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71919. }
  71920. }
  71921. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71922. };
  71923. Skeleton.prototype.prepare = function () {
  71924. if (!this._isDirty) {
  71925. return;
  71926. }
  71927. if (this.needInitialSkinMatrix) {
  71928. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71929. var mesh = this._meshesWithPoseMatrix[index];
  71930. var poseMatrix = mesh.getPoseMatrix();
  71931. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71932. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71933. }
  71934. if (this._synchronizedWithMesh !== mesh) {
  71935. this._synchronizedWithMesh = mesh;
  71936. // Prepare bones
  71937. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71938. var bone = this.bones[boneIndex];
  71939. if (!bone.getParent()) {
  71940. var matrix = bone.getBaseMatrix();
  71941. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71942. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71943. }
  71944. }
  71945. }
  71946. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71947. }
  71948. }
  71949. else {
  71950. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71951. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71952. }
  71953. this._computeTransformMatrices(this._transformMatrices, null);
  71954. }
  71955. this._isDirty = false;
  71956. this._scene._activeBones.addCount(this.bones.length, false);
  71957. };
  71958. Skeleton.prototype.getAnimatables = function () {
  71959. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71960. this._animatables = [];
  71961. for (var index = 0; index < this.bones.length; index++) {
  71962. this._animatables.push(this.bones[index]);
  71963. }
  71964. }
  71965. return this._animatables;
  71966. };
  71967. Skeleton.prototype.clone = function (name, id) {
  71968. var result = new Skeleton(name, id || name, this._scene);
  71969. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71970. for (var index = 0; index < this.bones.length; index++) {
  71971. var source = this.bones[index];
  71972. var parentBone = null;
  71973. var parent_1 = source.getParent();
  71974. if (parent_1) {
  71975. var parentIndex = this.bones.indexOf(parent_1);
  71976. parentBone = result.bones[parentIndex];
  71977. }
  71978. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71979. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71980. }
  71981. if (this._ranges) {
  71982. result._ranges = {};
  71983. for (var rangeName in this._ranges) {
  71984. var range = this._ranges[rangeName];
  71985. if (range) {
  71986. result._ranges[rangeName] = range.clone();
  71987. }
  71988. }
  71989. }
  71990. this._isDirty = true;
  71991. return result;
  71992. };
  71993. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71994. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71995. this.bones.forEach(function (bone) {
  71996. bone.animations.forEach(function (animation) {
  71997. animation.enableBlending = true;
  71998. animation.blendingSpeed = blendingSpeed;
  71999. });
  72000. });
  72001. };
  72002. Skeleton.prototype.dispose = function () {
  72003. this._meshesWithPoseMatrix = [];
  72004. // Animations
  72005. this.getScene().stopAnimation(this);
  72006. // Remove from scene
  72007. this.getScene().removeSkeleton(this);
  72008. };
  72009. Skeleton.prototype.serialize = function () {
  72010. var serializationObject = {};
  72011. serializationObject.name = this.name;
  72012. serializationObject.id = this.id;
  72013. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72014. serializationObject.bones = [];
  72015. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72016. for (var index = 0; index < this.bones.length; index++) {
  72017. var bone = this.bones[index];
  72018. var parent_2 = bone.getParent();
  72019. var serializedBone = {
  72020. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72021. name: bone.name,
  72022. matrix: bone.getBaseMatrix().toArray(),
  72023. rest: bone.getRestPose().toArray()
  72024. };
  72025. serializationObject.bones.push(serializedBone);
  72026. if (bone.length) {
  72027. serializedBone.length = bone.length;
  72028. }
  72029. if (bone.animations && bone.animations.length > 0) {
  72030. serializedBone.animation = bone.animations[0].serialize();
  72031. }
  72032. serializationObject.ranges = [];
  72033. for (var name in this._ranges) {
  72034. var source = this._ranges[name];
  72035. if (!source) {
  72036. continue;
  72037. }
  72038. var range = {};
  72039. range.name = name;
  72040. range.from = source.from;
  72041. range.to = source.to;
  72042. serializationObject.ranges.push(range);
  72043. }
  72044. }
  72045. return serializationObject;
  72046. };
  72047. Skeleton.Parse = function (parsedSkeleton, scene) {
  72048. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72049. if (parsedSkeleton.dimensionsAtRest) {
  72050. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72051. }
  72052. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72053. var index;
  72054. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72055. var parsedBone = parsedSkeleton.bones[index];
  72056. var parentBone = null;
  72057. if (parsedBone.parentBoneIndex > -1) {
  72058. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72059. }
  72060. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72061. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72062. if (parsedBone.length) {
  72063. bone.length = parsedBone.length;
  72064. }
  72065. if (parsedBone.animation) {
  72066. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72067. }
  72068. }
  72069. // placed after bones, so createAnimationRange can cascade down
  72070. if (parsedSkeleton.ranges) {
  72071. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72072. var data = parsedSkeleton.ranges[index];
  72073. skeleton.createAnimationRange(data.name, data.from, data.to);
  72074. }
  72075. }
  72076. return skeleton;
  72077. };
  72078. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72079. if (forceUpdate === void 0) { forceUpdate = false; }
  72080. var renderId = this._scene.getRenderId();
  72081. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72082. this.bones[0].computeAbsoluteTransforms();
  72083. this._lastAbsoluteTransformsUpdateId = renderId;
  72084. }
  72085. };
  72086. Skeleton.prototype.getPoseMatrix = function () {
  72087. var poseMatrix = null;
  72088. if (this._meshesWithPoseMatrix.length > 0) {
  72089. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72090. }
  72091. return poseMatrix;
  72092. };
  72093. Skeleton.prototype.sortBones = function () {
  72094. var bones = new Array();
  72095. var visited = new Array(this.bones.length);
  72096. for (var index = 0; index < this.bones.length; index++) {
  72097. this._sortBones(index, bones, visited);
  72098. }
  72099. this.bones = bones;
  72100. };
  72101. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72102. if (visited[index]) {
  72103. return;
  72104. }
  72105. visited[index] = true;
  72106. var bone = this.bones[index];
  72107. if (bone._index === undefined) {
  72108. bone._index = index;
  72109. }
  72110. var parentBone = bone.getParent();
  72111. if (parentBone) {
  72112. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72113. }
  72114. bones.push(bone);
  72115. };
  72116. return Skeleton;
  72117. }());
  72118. BABYLON.Skeleton = Skeleton;
  72119. })(BABYLON || (BABYLON = {}));
  72120. //# sourceMappingURL=babylon.skeleton.js.map
  72121. var BABYLON;
  72122. (function (BABYLON) {
  72123. var SphericalPolynomial = /** @class */ (function () {
  72124. function SphericalPolynomial() {
  72125. this.x = BABYLON.Vector3.Zero();
  72126. this.y = BABYLON.Vector3.Zero();
  72127. this.z = BABYLON.Vector3.Zero();
  72128. this.xx = BABYLON.Vector3.Zero();
  72129. this.yy = BABYLON.Vector3.Zero();
  72130. this.zz = BABYLON.Vector3.Zero();
  72131. this.xy = BABYLON.Vector3.Zero();
  72132. this.yz = BABYLON.Vector3.Zero();
  72133. this.zx = BABYLON.Vector3.Zero();
  72134. }
  72135. SphericalPolynomial.prototype.addAmbient = function (color) {
  72136. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72137. this.xx = this.xx.add(colorVector);
  72138. this.yy = this.yy.add(colorVector);
  72139. this.zz = this.zz.add(colorVector);
  72140. };
  72141. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72142. var result = new SphericalPolynomial();
  72143. result.x = harmonics.L11.scale(1.02333);
  72144. result.y = harmonics.L1_1.scale(1.02333);
  72145. result.z = harmonics.L10.scale(1.02333);
  72146. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72147. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72148. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72149. result.yz = harmonics.L2_1.scale(0.858086);
  72150. result.zx = harmonics.L21.scale(0.858086);
  72151. result.xy = harmonics.L2_2.scale(0.858086);
  72152. result.scale(1.0 / Math.PI);
  72153. return result;
  72154. };
  72155. SphericalPolynomial.prototype.scale = function (scale) {
  72156. this.x = this.x.scale(scale);
  72157. this.y = this.y.scale(scale);
  72158. this.z = this.z.scale(scale);
  72159. this.xx = this.xx.scale(scale);
  72160. this.yy = this.yy.scale(scale);
  72161. this.zz = this.zz.scale(scale);
  72162. this.yz = this.yz.scale(scale);
  72163. this.zx = this.zx.scale(scale);
  72164. this.xy = this.xy.scale(scale);
  72165. };
  72166. return SphericalPolynomial;
  72167. }());
  72168. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72169. var SphericalHarmonics = /** @class */ (function () {
  72170. function SphericalHarmonics() {
  72171. this.L00 = BABYLON.Vector3.Zero();
  72172. this.L1_1 = BABYLON.Vector3.Zero();
  72173. this.L10 = BABYLON.Vector3.Zero();
  72174. this.L11 = BABYLON.Vector3.Zero();
  72175. this.L2_2 = BABYLON.Vector3.Zero();
  72176. this.L2_1 = BABYLON.Vector3.Zero();
  72177. this.L20 = BABYLON.Vector3.Zero();
  72178. this.L21 = BABYLON.Vector3.Zero();
  72179. this.L22 = BABYLON.Vector3.Zero();
  72180. }
  72181. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72182. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72183. var c = colorVector.scale(deltaSolidAngle);
  72184. this.L00 = this.L00.add(c.scale(0.282095));
  72185. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72186. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72187. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72188. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72189. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72190. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72191. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72192. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72193. };
  72194. SphericalHarmonics.prototype.scale = function (scale) {
  72195. this.L00 = this.L00.scale(scale);
  72196. this.L1_1 = this.L1_1.scale(scale);
  72197. this.L10 = this.L10.scale(scale);
  72198. this.L11 = this.L11.scale(scale);
  72199. this.L2_2 = this.L2_2.scale(scale);
  72200. this.L2_1 = this.L2_1.scale(scale);
  72201. this.L20 = this.L20.scale(scale);
  72202. this.L21 = this.L21.scale(scale);
  72203. this.L22 = this.L22.scale(scale);
  72204. };
  72205. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72206. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72207. //
  72208. // E_lm = A_l * L_lm
  72209. //
  72210. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72211. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72212. // the scaling factors are given in equation 9.
  72213. // Constant (Band 0)
  72214. this.L00 = this.L00.scale(3.141593);
  72215. // Linear (Band 1)
  72216. this.L1_1 = this.L1_1.scale(2.094395);
  72217. this.L10 = this.L10.scale(2.094395);
  72218. this.L11 = this.L11.scale(2.094395);
  72219. // Quadratic (Band 2)
  72220. this.L2_2 = this.L2_2.scale(0.785398);
  72221. this.L2_1 = this.L2_1.scale(0.785398);
  72222. this.L20 = this.L20.scale(0.785398);
  72223. this.L21 = this.L21.scale(0.785398);
  72224. this.L22 = this.L22.scale(0.785398);
  72225. };
  72226. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72227. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72228. // L = (1/pi) * E * rho
  72229. //
  72230. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72231. this.scale(1.0 / Math.PI);
  72232. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72233. // (The pixel shader must apply albedo after texture fetches, etc).
  72234. };
  72235. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72236. var result = new SphericalHarmonics();
  72237. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72238. result.L1_1 = polynomial.y.scale(0.977204);
  72239. result.L10 = polynomial.z.scale(0.977204);
  72240. result.L11 = polynomial.x.scale(0.977204);
  72241. result.L2_2 = polynomial.xy.scale(1.16538);
  72242. result.L2_1 = polynomial.yz.scale(1.16538);
  72243. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72244. result.L21 = polynomial.zx.scale(1.16538);
  72245. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72246. result.scale(Math.PI);
  72247. return result;
  72248. };
  72249. return SphericalHarmonics;
  72250. }());
  72251. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72252. })(BABYLON || (BABYLON = {}));
  72253. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72254. var BABYLON;
  72255. (function (BABYLON) {
  72256. var FileFaceOrientation = /** @class */ (function () {
  72257. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72258. this.name = name;
  72259. this.worldAxisForNormal = worldAxisForNormal;
  72260. this.worldAxisForFileX = worldAxisForFileX;
  72261. this.worldAxisForFileY = worldAxisForFileY;
  72262. }
  72263. return FileFaceOrientation;
  72264. }());
  72265. ;
  72266. /**
  72267. * Helper class dealing with the extraction of spherical polynomial dataArray
  72268. * from a cube map.
  72269. */
  72270. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72271. function CubeMapToSphericalPolynomialTools() {
  72272. }
  72273. /**
  72274. * Converts a texture to the according Spherical Polynomial data.
  72275. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72276. *
  72277. * @param texture The texture to extract the information from.
  72278. * @return The Spherical Polynomial data.
  72279. */
  72280. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72281. if (!texture.isCube) {
  72282. // Only supports cube Textures currently.
  72283. return null;
  72284. }
  72285. var size = texture.getSize().width;
  72286. var right = texture.readPixels(0);
  72287. var left = texture.readPixels(1);
  72288. var up;
  72289. var down;
  72290. if (texture.isRenderTarget) {
  72291. up = texture.readPixels(3);
  72292. down = texture.readPixels(2);
  72293. }
  72294. else {
  72295. up = texture.readPixels(2);
  72296. down = texture.readPixels(3);
  72297. }
  72298. var front = texture.readPixels(4);
  72299. var back = texture.readPixels(5);
  72300. var gammaSpace = texture.gammaSpace;
  72301. // Always read as RGBA.
  72302. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72303. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72304. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72305. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72306. }
  72307. var cubeInfo = {
  72308. size: size,
  72309. right: right,
  72310. left: left,
  72311. up: up,
  72312. down: down,
  72313. front: front,
  72314. back: back,
  72315. format: format,
  72316. type: type,
  72317. gammaSpace: gammaSpace,
  72318. };
  72319. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72320. };
  72321. /**
  72322. * Converts a cubemap to the according Spherical Polynomial data.
  72323. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72324. *
  72325. * @param cubeInfo The Cube map to extract the information from.
  72326. * @return The Spherical Polynomial data.
  72327. */
  72328. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72329. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72330. var totalSolidAngle = 0.0;
  72331. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72332. var du = 2.0 / cubeInfo.size;
  72333. var dv = du;
  72334. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72335. var minUV = du * 0.5 - 1.0;
  72336. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72337. var fileFace = this.FileFaces[faceIndex];
  72338. var dataArray = cubeInfo[fileFace.name];
  72339. var v = minUV;
  72340. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72341. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72342. // Because SP is still linear, so summation is fine in that basis.
  72343. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72344. for (var y = 0; y < cubeInfo.size; y++) {
  72345. var u = minUV;
  72346. for (var x = 0; x < cubeInfo.size; x++) {
  72347. // World direction (not normalised)
  72348. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72349. worldDirection.normalize();
  72350. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72351. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72352. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72353. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72354. // Handle Integer types.
  72355. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72356. r /= 255;
  72357. g /= 255;
  72358. b /= 255;
  72359. }
  72360. // Handle Gamma space textures.
  72361. if (cubeInfo.gammaSpace) {
  72362. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72363. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72364. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72365. }
  72366. var color = new BABYLON.Color3(r, g, b);
  72367. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72368. totalSolidAngle += deltaSolidAngle;
  72369. u += du;
  72370. }
  72371. v += dv;
  72372. }
  72373. }
  72374. // Solid angle for entire sphere is 4*pi
  72375. var sphereSolidAngle = 4.0 * Math.PI;
  72376. // Adjust the solid angle to allow for how many faces we processed.
  72377. var facesProcessed = 6.0;
  72378. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72379. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72380. // This is needed because the numerical integration over the cube uses a
  72381. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72382. // and also to compensate for accumulative error due to float precision in the summation.
  72383. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72384. sphericalHarmonics.scale(correctionFactor);
  72385. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72386. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72387. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72388. };
  72389. CubeMapToSphericalPolynomialTools.FileFaces = [
  72390. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72391. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72392. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72393. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72394. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72395. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72396. ];
  72397. return CubeMapToSphericalPolynomialTools;
  72398. }());
  72399. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72400. })(BABYLON || (BABYLON = {}));
  72401. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72402. var BABYLON;
  72403. (function (BABYLON) {
  72404. /**
  72405. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72406. */
  72407. var PanoramaToCubeMapTools = /** @class */ (function () {
  72408. function PanoramaToCubeMapTools() {
  72409. }
  72410. /**
  72411. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72412. *
  72413. * @param float32Array The source data.
  72414. * @param inputWidth The width of the input panorama.
  72415. * @param inputhHeight The height of the input panorama.
  72416. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72417. * @return The cubemap data
  72418. */
  72419. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72420. if (!float32Array) {
  72421. throw "ConvertPanoramaToCubemap: input cannot be null";
  72422. }
  72423. if (float32Array.length != inputWidth * inputHeight * 3) {
  72424. throw "ConvertPanoramaToCubemap: input size is wrong";
  72425. }
  72426. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72427. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72428. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72429. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72430. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72431. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72432. return {
  72433. front: textureFront,
  72434. back: textureBack,
  72435. left: textureLeft,
  72436. right: textureRight,
  72437. up: textureUp,
  72438. down: textureDown,
  72439. size: size,
  72440. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72441. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72442. gammaSpace: false,
  72443. };
  72444. };
  72445. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72446. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72447. var textureArray = new Float32Array(buffer);
  72448. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72449. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72450. var dy = 1 / texSize;
  72451. var fy = 0;
  72452. for (var y = 0; y < texSize; y++) {
  72453. var xv1 = faceData[0];
  72454. var xv2 = faceData[2];
  72455. for (var x = 0; x < texSize; x++) {
  72456. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72457. v.normalize();
  72458. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72459. // 3 channels per pixels
  72460. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72461. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72462. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72463. xv1 = xv1.add(rotDX1);
  72464. xv2 = xv2.add(rotDX2);
  72465. }
  72466. fy += dy;
  72467. }
  72468. return textureArray;
  72469. };
  72470. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72471. var theta = Math.atan2(vDir.z, vDir.x);
  72472. var phi = Math.acos(vDir.y);
  72473. while (theta < -Math.PI)
  72474. theta += 2 * Math.PI;
  72475. while (theta > Math.PI)
  72476. theta -= 2 * Math.PI;
  72477. var dx = theta / Math.PI;
  72478. var dy = phi / Math.PI;
  72479. // recenter.
  72480. dx = dx * 0.5 + 0.5;
  72481. var px = Math.round(dx * inputWidth);
  72482. if (px < 0)
  72483. px = 0;
  72484. else if (px >= inputWidth)
  72485. px = inputWidth - 1;
  72486. var py = Math.round(dy * inputHeight);
  72487. if (py < 0)
  72488. py = 0;
  72489. else if (py >= inputHeight)
  72490. py = inputHeight - 1;
  72491. var inputY = (inputHeight - py - 1);
  72492. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72493. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72494. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72495. return {
  72496. r: r,
  72497. g: g,
  72498. b: b
  72499. };
  72500. };
  72501. PanoramaToCubeMapTools.FACE_FRONT = [
  72502. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72503. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72504. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72505. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72506. ];
  72507. PanoramaToCubeMapTools.FACE_BACK = [
  72508. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72509. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72510. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72511. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72512. ];
  72513. PanoramaToCubeMapTools.FACE_RIGHT = [
  72514. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72515. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72516. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72517. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72518. ];
  72519. PanoramaToCubeMapTools.FACE_LEFT = [
  72520. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72521. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72522. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72523. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72524. ];
  72525. PanoramaToCubeMapTools.FACE_DOWN = [
  72526. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72527. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72528. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72529. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72530. ];
  72531. PanoramaToCubeMapTools.FACE_UP = [
  72532. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72533. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72534. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72535. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72536. ];
  72537. return PanoramaToCubeMapTools;
  72538. }());
  72539. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72540. })(BABYLON || (BABYLON = {}));
  72541. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72542. var BABYLON;
  72543. (function (BABYLON) {
  72544. ;
  72545. /**
  72546. * This groups tools to convert HDR texture to native colors array.
  72547. */
  72548. var HDRTools = /** @class */ (function () {
  72549. function HDRTools() {
  72550. }
  72551. HDRTools.Ldexp = function (mantissa, exponent) {
  72552. if (exponent > 1023) {
  72553. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72554. }
  72555. if (exponent < -1074) {
  72556. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72557. }
  72558. return mantissa * Math.pow(2, exponent);
  72559. };
  72560. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72561. if (exponent > 0) {
  72562. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72563. float32array[index + 0] = red * exponent;
  72564. float32array[index + 1] = green * exponent;
  72565. float32array[index + 2] = blue * exponent;
  72566. }
  72567. else {
  72568. float32array[index + 0] = 0;
  72569. float32array[index + 1] = 0;
  72570. float32array[index + 2] = 0;
  72571. }
  72572. };
  72573. HDRTools.readStringLine = function (uint8array, startIndex) {
  72574. var line = "";
  72575. var character = "";
  72576. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72577. character = String.fromCharCode(uint8array[i]);
  72578. if (character == "\n") {
  72579. break;
  72580. }
  72581. line += character;
  72582. }
  72583. return line;
  72584. };
  72585. /**
  72586. * Reads header information from an RGBE texture stored in a native array.
  72587. * More information on this format are available here:
  72588. * https://en.wikipedia.org/wiki/RGBE_image_format
  72589. *
  72590. * @param uint8array The binary file stored in native array.
  72591. * @return The header information.
  72592. */
  72593. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72594. var height = 0;
  72595. var width = 0;
  72596. var line = this.readStringLine(uint8array, 0);
  72597. if (line[0] != '#' || line[1] != '?') {
  72598. throw "Bad HDR Format.";
  72599. }
  72600. var endOfHeader = false;
  72601. var findFormat = false;
  72602. var lineIndex = 0;
  72603. do {
  72604. lineIndex += (line.length + 1);
  72605. line = this.readStringLine(uint8array, lineIndex);
  72606. if (line == "FORMAT=32-bit_rle_rgbe") {
  72607. findFormat = true;
  72608. }
  72609. else if (line.length == 0) {
  72610. endOfHeader = true;
  72611. }
  72612. } while (!endOfHeader);
  72613. if (!findFormat) {
  72614. throw "HDR Bad header format, unsupported FORMAT";
  72615. }
  72616. lineIndex += (line.length + 1);
  72617. line = this.readStringLine(uint8array, lineIndex);
  72618. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72619. var match = sizeRegexp.exec(line);
  72620. // TODO. Support +Y and -X if needed.
  72621. if (!match || match.length < 3) {
  72622. throw "HDR Bad header format, no size";
  72623. }
  72624. width = parseInt(match[2]);
  72625. height = parseInt(match[1]);
  72626. if (width < 8 || width > 0x7fff) {
  72627. throw "HDR Bad header format, unsupported size";
  72628. }
  72629. lineIndex += (line.length + 1);
  72630. return {
  72631. height: height,
  72632. width: width,
  72633. dataPosition: lineIndex
  72634. };
  72635. };
  72636. /**
  72637. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72638. * This RGBE texture needs to store the information as a panorama.
  72639. *
  72640. * More information on this format are available here:
  72641. * https://en.wikipedia.org/wiki/RGBE_image_format
  72642. *
  72643. * @param buffer The binary file stored in an array buffer.
  72644. * @param size The expected size of the extracted cubemap.
  72645. * @return The Cube Map information.
  72646. */
  72647. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72648. var uint8array = new Uint8Array(buffer);
  72649. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72650. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72651. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72652. return cubeMapData;
  72653. };
  72654. /**
  72655. * Returns the pixels data extracted from an RGBE texture.
  72656. * This pixels will be stored left to right up to down in the R G B order in one array.
  72657. *
  72658. * More information on this format are available here:
  72659. * https://en.wikipedia.org/wiki/RGBE_image_format
  72660. *
  72661. * @param uint8array The binary file stored in an array buffer.
  72662. * @param hdrInfo The header information of the file.
  72663. * @return The pixels data in RGB right to left up to down order.
  72664. */
  72665. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72666. // Keep for multi format supports.
  72667. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72668. };
  72669. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72670. var num_scanlines = hdrInfo.height;
  72671. var scanline_width = hdrInfo.width;
  72672. var a, b, c, d, count;
  72673. var dataIndex = hdrInfo.dataPosition;
  72674. var index = 0, endIndex = 0, i = 0;
  72675. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72676. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72677. // 3 channels of 4 bytes per pixel in float.
  72678. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72679. var resultArray = new Float32Array(resultBuffer);
  72680. // read in each successive scanline
  72681. while (num_scanlines > 0) {
  72682. a = uint8array[dataIndex++];
  72683. b = uint8array[dataIndex++];
  72684. c = uint8array[dataIndex++];
  72685. d = uint8array[dataIndex++];
  72686. if (a != 2 || b != 2 || (c & 0x80)) {
  72687. // this file is not run length encoded
  72688. throw "HDR Bad header format, not RLE";
  72689. }
  72690. if (((c << 8) | d) != scanline_width) {
  72691. throw "HDR Bad header format, wrong scan line width";
  72692. }
  72693. index = 0;
  72694. // read each of the four channels for the scanline into the buffer
  72695. for (i = 0; i < 4; i++) {
  72696. endIndex = (i + 1) * scanline_width;
  72697. while (index < endIndex) {
  72698. a = uint8array[dataIndex++];
  72699. b = uint8array[dataIndex++];
  72700. if (a > 128) {
  72701. // a run of the same value
  72702. count = a - 128;
  72703. if ((count == 0) || (count > endIndex - index)) {
  72704. throw "HDR Bad Format, bad scanline data (run)";
  72705. }
  72706. while (count-- > 0) {
  72707. scanLineArray[index++] = b;
  72708. }
  72709. }
  72710. else {
  72711. // a non-run
  72712. count = a;
  72713. if ((count == 0) || (count > endIndex - index)) {
  72714. throw "HDR Bad Format, bad scanline data (non-run)";
  72715. }
  72716. scanLineArray[index++] = b;
  72717. if (--count > 0) {
  72718. for (var j = 0; j < count; j++) {
  72719. scanLineArray[index++] = uint8array[dataIndex++];
  72720. }
  72721. }
  72722. }
  72723. }
  72724. }
  72725. // now convert data from buffer into floats
  72726. for (i = 0; i < scanline_width; i++) {
  72727. a = scanLineArray[i];
  72728. b = scanLineArray[i + scanline_width];
  72729. c = scanLineArray[i + 2 * scanline_width];
  72730. d = scanLineArray[i + 3 * scanline_width];
  72731. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72732. }
  72733. num_scanlines--;
  72734. }
  72735. return resultArray;
  72736. };
  72737. return HDRTools;
  72738. }());
  72739. BABYLON.HDRTools = HDRTools;
  72740. })(BABYLON || (BABYLON = {}));
  72741. //# sourceMappingURL=babylon.hdr.js.map
  72742. var BABYLON;
  72743. (function (BABYLON) {
  72744. /**
  72745. * This represents a texture coming from an HDR input.
  72746. *
  72747. * The only supported format is currently panorama picture stored in RGBE format.
  72748. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72749. */
  72750. var HDRCubeTexture = /** @class */ (function (_super) {
  72751. __extends(HDRCubeTexture, _super);
  72752. /**
  72753. * Instantiates an HDRTexture from the following parameters.
  72754. *
  72755. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72756. * @param scene The scene the texture will be used in
  72757. * @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.
  72758. * @param noMipmap Forces to not generate the mipmap if true
  72759. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72760. * @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)
  72761. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72762. */
  72763. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72764. if (noMipmap === void 0) { noMipmap = false; }
  72765. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72766. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72767. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72768. if (onLoad === void 0) { onLoad = null; }
  72769. if (onError === void 0) { onError = null; }
  72770. var _this = _super.call(this, scene) || this;
  72771. _this._useInGammaSpace = false;
  72772. _this._generateHarmonics = true;
  72773. _this._isBABYLONPreprocessed = false;
  72774. _this._onLoad = null;
  72775. _this._onError = null;
  72776. /**
  72777. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72778. */
  72779. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72780. /**
  72781. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72782. * This is usefull at run time to apply the good shader.
  72783. */
  72784. _this.isPMREM = false;
  72785. _this._isBlocking = true;
  72786. /**
  72787. * Gets or sets the center of the bounding box associated with the cube texture
  72788. * It must define where the camera used to render the texture was set
  72789. */
  72790. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72791. if (!url) {
  72792. return _this;
  72793. }
  72794. _this.name = url;
  72795. _this.url = url;
  72796. _this.hasAlpha = false;
  72797. _this.isCube = true;
  72798. _this._textureMatrix = BABYLON.Matrix.Identity();
  72799. _this._onLoad = onLoad;
  72800. _this._onError = onError;
  72801. _this.gammaSpace = false;
  72802. var caps = scene.getEngine().getCaps();
  72803. if (size) {
  72804. _this._isBABYLONPreprocessed = false;
  72805. _this._noMipmap = noMipmap;
  72806. _this._size = size;
  72807. _this._useInGammaSpace = useInGammaSpace;
  72808. _this._usePMREMGenerator = usePMREMGenerator &&
  72809. caps.textureLOD &&
  72810. caps.textureFloat &&
  72811. !_this._useInGammaSpace;
  72812. }
  72813. else {
  72814. _this._isBABYLONPreprocessed = true;
  72815. _this._noMipmap = false;
  72816. _this._useInGammaSpace = false;
  72817. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72818. !_this._useInGammaSpace;
  72819. }
  72820. _this.isPMREM = _this._usePMREMGenerator;
  72821. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72822. if (!_this._texture) {
  72823. if (!scene.useDelayedTextureLoading) {
  72824. _this.loadTexture();
  72825. }
  72826. else {
  72827. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72828. }
  72829. }
  72830. return _this;
  72831. }
  72832. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72833. /**
  72834. * Gets wether or not the texture is blocking during loading.
  72835. */
  72836. get: function () {
  72837. return this._isBlocking;
  72838. },
  72839. /**
  72840. * Sets wether or not the texture is blocking during loading.
  72841. */
  72842. set: function (value) {
  72843. this._isBlocking = value;
  72844. },
  72845. enumerable: true,
  72846. configurable: true
  72847. });
  72848. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72849. get: function () {
  72850. return this._boundingBoxSize;
  72851. },
  72852. /**
  72853. * Gets or sets the size of the bounding box associated with the cube texture
  72854. * When defined, the cubemap will switch to local mode
  72855. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72856. * @example https://www.babylonjs-playground.com/#RNASML
  72857. */
  72858. set: function (value) {
  72859. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72860. return;
  72861. }
  72862. this._boundingBoxSize = value;
  72863. var scene = this.getScene();
  72864. if (scene) {
  72865. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72866. }
  72867. },
  72868. enumerable: true,
  72869. configurable: true
  72870. });
  72871. /**
  72872. * Occurs when the file is a preprocessed .babylon.hdr file.
  72873. */
  72874. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72875. var _this = this;
  72876. var mipLevels = 0;
  72877. var floatArrayView = null;
  72878. var scene = this.getScene();
  72879. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72880. var mips = new Array();
  72881. if (!floatArrayView) {
  72882. return mips;
  72883. }
  72884. var startIndex = 30;
  72885. for (var level = 0; level < mipLevels; level++) {
  72886. mips.push([]);
  72887. // Fill each pixel of the mip level.
  72888. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72889. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72890. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72891. mips[level].push(faceData);
  72892. startIndex += faceSize;
  72893. }
  72894. }
  72895. return mips;
  72896. } : null;
  72897. var callback = function (buffer) {
  72898. var scene = _this.getScene();
  72899. if (!scene) {
  72900. return null;
  72901. }
  72902. // Create Native Array Views
  72903. var intArrayView = new Int32Array(buffer);
  72904. floatArrayView = new Float32Array(buffer);
  72905. // Fill header.
  72906. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72907. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72908. // Update Texture Information.
  72909. if (!_this._texture) {
  72910. return null;
  72911. }
  72912. _this._texture.updateSize(_this._size, _this._size);
  72913. // Fill polynomial information.
  72914. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72915. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72916. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72917. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72918. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72919. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72920. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72921. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72922. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72923. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72924. _this.sphericalPolynomial = sphericalPolynomial;
  72925. // Fill pixel data.
  72926. mipLevels = intArrayView[29]; // Number of mip levels.
  72927. var startIndex = 30;
  72928. var data = [];
  72929. var faceSize = Math.pow(_this._size, 2) * 3;
  72930. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72931. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72932. startIndex += faceSize;
  72933. }
  72934. var results = [];
  72935. var byteArray = null;
  72936. // Push each faces.
  72937. for (var k = 0; k < 6; k++) {
  72938. var dataFace = null;
  72939. // To be deprecated.
  72940. if (version === 1) {
  72941. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72942. dataFace = data[j];
  72943. }
  72944. // If special cases.
  72945. if (!mipmapGenerator && dataFace) {
  72946. if (!scene.getEngine().getCaps().textureFloat) {
  72947. // 3 channels of 1 bytes per pixel in bytes.
  72948. var byteBuffer = new ArrayBuffer(faceSize);
  72949. byteArray = new Uint8Array(byteBuffer);
  72950. }
  72951. for (var i = 0; i < _this._size * _this._size; i++) {
  72952. // Put in gamma space if requested.
  72953. if (_this._useInGammaSpace) {
  72954. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72955. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72956. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72957. }
  72958. // Convert to int texture for fallback.
  72959. if (byteArray) {
  72960. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72961. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72962. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72963. // May use luminance instead if the result is not accurate.
  72964. var max = Math.max(Math.max(r, g), b);
  72965. if (max > 255) {
  72966. var scale = 255 / max;
  72967. r *= scale;
  72968. g *= scale;
  72969. b *= scale;
  72970. }
  72971. byteArray[(i * 3) + 0] = r;
  72972. byteArray[(i * 3) + 1] = g;
  72973. byteArray[(i * 3) + 2] = b;
  72974. }
  72975. }
  72976. }
  72977. // Fill the array accordingly.
  72978. if (byteArray) {
  72979. results.push(byteArray);
  72980. }
  72981. else {
  72982. results.push(dataFace);
  72983. }
  72984. }
  72985. return results;
  72986. };
  72987. if (scene) {
  72988. 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);
  72989. }
  72990. };
  72991. /**
  72992. * Occurs when the file is raw .hdr file.
  72993. */
  72994. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72995. var _this = this;
  72996. var callback = function (buffer) {
  72997. var scene = _this.getScene();
  72998. if (!scene) {
  72999. return null;
  73000. }
  73001. // Extract the raw linear data.
  73002. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73003. // Generate harmonics if needed.
  73004. if (_this._generateHarmonics) {
  73005. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73006. _this.sphericalPolynomial = sphericalPolynomial;
  73007. }
  73008. var results = [];
  73009. var byteArray = null;
  73010. // Push each faces.
  73011. for (var j = 0; j < 6; j++) {
  73012. // Create uintarray fallback.
  73013. if (!scene.getEngine().getCaps().textureFloat) {
  73014. // 3 channels of 1 bytes per pixel in bytes.
  73015. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73016. byteArray = new Uint8Array(byteBuffer);
  73017. }
  73018. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73019. // If special cases.
  73020. if (_this._useInGammaSpace || byteArray) {
  73021. for (var i = 0; i < _this._size * _this._size; i++) {
  73022. // Put in gamma space if requested.
  73023. if (_this._useInGammaSpace) {
  73024. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73025. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73026. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73027. }
  73028. // Convert to int texture for fallback.
  73029. if (byteArray) {
  73030. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73031. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73032. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73033. // May use luminance instead if the result is not accurate.
  73034. var max = Math.max(Math.max(r, g), b);
  73035. if (max > 255) {
  73036. var scale = 255 / max;
  73037. r *= scale;
  73038. g *= scale;
  73039. b *= scale;
  73040. }
  73041. byteArray[(i * 3) + 0] = r;
  73042. byteArray[(i * 3) + 1] = g;
  73043. byteArray[(i * 3) + 2] = b;
  73044. }
  73045. }
  73046. }
  73047. if (byteArray) {
  73048. results.push(byteArray);
  73049. }
  73050. else {
  73051. results.push(dataFace);
  73052. }
  73053. }
  73054. return results;
  73055. };
  73056. var mipmapGenerator = null;
  73057. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73058. // if (!this._noMipmap &&
  73059. // this._usePMREMGenerator) {
  73060. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73061. // // Custom setup of the generator matching with the PBR shader values.
  73062. // var generator = new BABYLON.PMREMGenerator(data,
  73063. // this._size,
  73064. // this._size,
  73065. // 0,
  73066. // 3,
  73067. // this.getScene().getEngine().getCaps().textureFloat,
  73068. // 2048,
  73069. // 0.25,
  73070. // false,
  73071. // true);
  73072. // return generator.filterCubeMap();
  73073. // };
  73074. // }
  73075. var scene = this.getScene();
  73076. if (scene) {
  73077. 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);
  73078. }
  73079. };
  73080. /**
  73081. * Starts the loading process of the texture.
  73082. */
  73083. HDRCubeTexture.prototype.loadTexture = function () {
  73084. if (this._isBABYLONPreprocessed) {
  73085. this.loadBabylonTexture();
  73086. }
  73087. else {
  73088. this.loadHDRTexture();
  73089. }
  73090. };
  73091. HDRCubeTexture.prototype.clone = function () {
  73092. var scene = this.getScene();
  73093. if (!scene) {
  73094. return this;
  73095. }
  73096. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73097. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73098. // Base texture
  73099. newTexture.level = this.level;
  73100. newTexture.wrapU = this.wrapU;
  73101. newTexture.wrapV = this.wrapV;
  73102. newTexture.coordinatesIndex = this.coordinatesIndex;
  73103. newTexture.coordinatesMode = this.coordinatesMode;
  73104. return newTexture;
  73105. };
  73106. // Methods
  73107. HDRCubeTexture.prototype.delayLoad = function () {
  73108. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73109. return;
  73110. }
  73111. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73112. this._texture = this._getFromCache(this.url, this._noMipmap);
  73113. if (!this._texture) {
  73114. this.loadTexture();
  73115. }
  73116. };
  73117. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73118. return this._textureMatrix;
  73119. };
  73120. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73121. this._textureMatrix = value;
  73122. };
  73123. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73124. var texture = null;
  73125. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73126. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73127. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73128. texture.name = parsedTexture.name;
  73129. texture.hasAlpha = parsedTexture.hasAlpha;
  73130. texture.level = parsedTexture.level;
  73131. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73132. texture.isBlocking = parsedTexture.isBlocking;
  73133. }
  73134. if (texture) {
  73135. if (parsedTexture.boundingBoxPosition) {
  73136. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73137. }
  73138. if (parsedTexture.boundingBoxSize) {
  73139. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73140. }
  73141. }
  73142. return texture;
  73143. };
  73144. HDRCubeTexture.prototype.serialize = function () {
  73145. if (!this.name) {
  73146. return null;
  73147. }
  73148. var serializationObject = {};
  73149. serializationObject.name = this.name;
  73150. serializationObject.hasAlpha = this.hasAlpha;
  73151. serializationObject.isCube = true;
  73152. serializationObject.level = this.level;
  73153. serializationObject.size = this._size;
  73154. serializationObject.coordinatesMode = this.coordinatesMode;
  73155. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73156. serializationObject.generateHarmonics = this._generateHarmonics;
  73157. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73158. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73159. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73160. serializationObject.noMipmap = this._noMipmap;
  73161. serializationObject.isBlocking = this._isBlocking;
  73162. return serializationObject;
  73163. };
  73164. /**
  73165. * Saves as a file the data contained in the texture in a binary format.
  73166. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73167. * as the spherical used in the lighting.
  73168. * @param url The HDR file url.
  73169. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73170. * @param onError Method called if any error happens during download.
  73171. * @return The packed binary data.
  73172. */
  73173. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73174. if (onError === void 0) { onError = null; }
  73175. var callback = function (buffer) {
  73176. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73177. // Returns a URL you can use as a href.
  73178. var objUrl = window.URL.createObjectURL(data);
  73179. // Simulates a link to it and click to dowload.
  73180. var a = document.createElement("a");
  73181. document.body.appendChild(a);
  73182. a.style.display = "none";
  73183. a.href = objUrl;
  73184. a.download = "envmap.babylon.hdr";
  73185. a.click();
  73186. };
  73187. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73188. };
  73189. /**
  73190. * Serializes the data contained in the texture in a binary format.
  73191. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73192. * as the spherical used in the lighting.
  73193. * @param url The HDR file url.
  73194. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73195. * @param onError Method called if any error happens during download.
  73196. * @return The packed binary data.
  73197. */
  73198. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73199. if (onError === void 0) { onError = null; }
  73200. // Needs the url tho create the texture.
  73201. if (!url) {
  73202. return;
  73203. }
  73204. // Check Power of two size.
  73205. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73206. return;
  73207. }
  73208. // Coming Back in 3.x.
  73209. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73210. };
  73211. HDRCubeTexture._facesMapping = [
  73212. "right",
  73213. "left",
  73214. "up",
  73215. "down",
  73216. "front",
  73217. "back"
  73218. ];
  73219. return HDRCubeTexture;
  73220. }(BABYLON.BaseTexture));
  73221. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73222. })(BABYLON || (BABYLON = {}));
  73223. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73224. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73225. // Huge respect for a such great lib.
  73226. // Earcut license:
  73227. // Copyright (c) 2016, Mapbox
  73228. //
  73229. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73230. // with or without fee is hereby granted, provided that the above copyright notice
  73231. // and this permission notice appear in all copies.
  73232. //
  73233. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73234. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73235. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73236. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73237. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73238. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73239. // THIS SOFTWARE.
  73240. var Earcut;
  73241. (function (Earcut) {
  73242. /**
  73243. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73244. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73245. * @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).
  73246. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73247. */
  73248. function earcut(data, holeIndices, dim) {
  73249. dim = dim || 2;
  73250. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73251. if (!outerNode)
  73252. return triangles;
  73253. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73254. if (hasHoles)
  73255. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73256. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73257. if (data.length > 80 * dim) {
  73258. minX = maxX = data[0];
  73259. minY = maxY = data[1];
  73260. for (var i = dim; i < outerLen; i += dim) {
  73261. x = data[i];
  73262. y = data[i + 1];
  73263. if (x < minX)
  73264. minX = x;
  73265. if (y < minY)
  73266. minY = y;
  73267. if (x > maxX)
  73268. maxX = x;
  73269. if (y > maxY)
  73270. maxY = y;
  73271. }
  73272. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73273. size = Math.max(maxX - minX, maxY - minY);
  73274. }
  73275. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73276. return triangles;
  73277. }
  73278. Earcut.earcut = earcut;
  73279. var Node = /** @class */ (function () {
  73280. function Node(i, x, y) {
  73281. this.i = i;
  73282. this.x = x;
  73283. this.y = y;
  73284. this.prev = null;
  73285. this.next = null;
  73286. this.z = null;
  73287. this.prevZ = null;
  73288. this.nextZ = null;
  73289. this.steiner = false;
  73290. }
  73291. return Node;
  73292. }());
  73293. // create a circular doubly linked list from polygon points in the specified winding order
  73294. function linkedList(data, start, end, dim, clockwise) {
  73295. var i, last = null;
  73296. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73297. for (i = start; i < end; i += dim)
  73298. last = insertNode(i, data[i], data[i + 1], last);
  73299. }
  73300. else {
  73301. for (i = end - dim; i >= start; i -= dim)
  73302. last = insertNode(i, data[i], data[i + 1], last);
  73303. }
  73304. if (last && equals(last, last.next)) {
  73305. removeNode(last);
  73306. last = last.next;
  73307. }
  73308. return last;
  73309. }
  73310. // eliminate colinear or duplicate points
  73311. function filterPoints(start, end) {
  73312. if (!start)
  73313. return start;
  73314. if (!end)
  73315. end = start;
  73316. var p = start, again;
  73317. do {
  73318. again = false;
  73319. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73320. removeNode(p);
  73321. p = end = p.prev;
  73322. if (p === p.next)
  73323. return undefined;
  73324. again = true;
  73325. }
  73326. else {
  73327. p = p.next;
  73328. }
  73329. } while (again || p !== end);
  73330. return end;
  73331. }
  73332. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73333. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73334. if (!ear)
  73335. return;
  73336. // interlink polygon nodes in z-order
  73337. if (!pass && size)
  73338. indexCurve(ear, minX, minY, size);
  73339. var stop = ear, prev, next;
  73340. // iterate through ears, slicing them one by one
  73341. while (ear.prev !== ear.next) {
  73342. prev = ear.prev;
  73343. next = ear.next;
  73344. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73345. // cut off the triangle
  73346. triangles.push(prev.i / dim);
  73347. triangles.push(ear.i / dim);
  73348. triangles.push(next.i / dim);
  73349. removeNode(ear);
  73350. // skipping the next vertice leads to less sliver triangles
  73351. ear = next.next;
  73352. stop = next.next;
  73353. continue;
  73354. }
  73355. ear = next;
  73356. // if we looped through the whole remaining polygon and can't find any more ears
  73357. if (ear === stop) {
  73358. // try filtering points and slicing again
  73359. if (!pass) {
  73360. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73361. // if this didn't work, try curing all small self-intersections locally
  73362. }
  73363. else if (pass === 1) {
  73364. ear = cureLocalIntersections(ear, triangles, dim);
  73365. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73366. // as a last resort, try splitting the remaining polygon into two
  73367. }
  73368. else if (pass === 2) {
  73369. splitEarcut(ear, triangles, dim, minX, minY, size);
  73370. }
  73371. break;
  73372. }
  73373. }
  73374. }
  73375. // check whether a polygon node forms a valid ear with adjacent nodes
  73376. function isEar(ear) {
  73377. var a = ear.prev, b = ear, c = ear.next;
  73378. if (area(a, b, c) >= 0)
  73379. return false; // reflex, can't be an ear
  73380. // now make sure we don't have other points inside the potential ear
  73381. var p = ear.next.next;
  73382. while (p !== ear.prev) {
  73383. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73384. area(p.prev, p, p.next) >= 0)
  73385. return false;
  73386. p = p.next;
  73387. }
  73388. return true;
  73389. }
  73390. function isEarHashed(ear, minX, minY, size) {
  73391. var a = ear.prev, b = ear, c = ear.next;
  73392. if (area(a, b, c) >= 0)
  73393. return false; // reflex, can't be an ear
  73394. // triangle bbox; min & max are calculated like this for speed
  73395. 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);
  73396. // z-order range for the current triangle bbox;
  73397. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73398. // first look for points inside the triangle in increasing z-order
  73399. var p = ear.nextZ;
  73400. while (p && p.z <= maxZ) {
  73401. if (p !== ear.prev &&
  73402. p !== ear.next &&
  73403. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73404. area(p.prev, p, p.next) >= 0)
  73405. return false;
  73406. p = p.nextZ;
  73407. }
  73408. // then look for points in decreasing z-order
  73409. p = ear.prevZ;
  73410. while (p && p.z >= minZ) {
  73411. if (p !== ear.prev &&
  73412. p !== ear.next &&
  73413. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73414. area(p.prev, p, p.next) >= 0)
  73415. return false;
  73416. p = p.prevZ;
  73417. }
  73418. return true;
  73419. }
  73420. // go through all polygon nodes and cure small local self-intersections
  73421. function cureLocalIntersections(start, triangles, dim) {
  73422. var p = start;
  73423. do {
  73424. var a = p.prev, b = p.next.next;
  73425. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73426. triangles.push(a.i / dim);
  73427. triangles.push(p.i / dim);
  73428. triangles.push(b.i / dim);
  73429. // remove two nodes involved
  73430. removeNode(p);
  73431. removeNode(p.next);
  73432. p = start = b;
  73433. }
  73434. p = p.next;
  73435. } while (p !== start);
  73436. return p;
  73437. }
  73438. // try splitting polygon into two and triangulate them independently
  73439. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73440. // look for a valid diagonal that divides the polygon into two
  73441. var a = start;
  73442. do {
  73443. var b = a.next.next;
  73444. while (b !== a.prev) {
  73445. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73446. // split the polygon in two by the diagonal
  73447. var c = splitPolygon(a, b);
  73448. // filter colinear points around the cuts
  73449. a = filterPoints(a, a.next);
  73450. c = filterPoints(c, c.next);
  73451. // run earcut on each half
  73452. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73453. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73454. return;
  73455. }
  73456. b = b.next;
  73457. }
  73458. a = a.next;
  73459. } while (a !== start);
  73460. }
  73461. // link every hole into the outer loop, producing a single-ring polygon without holes
  73462. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73463. var queue = [], i, len, start, end, list;
  73464. for (i = 0, len = holeIndices.length; i < len; i++) {
  73465. start = holeIndices[i] * dim;
  73466. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73467. list = linkedList(data, start, end, dim, false);
  73468. if (list === list.next)
  73469. list.steiner = true;
  73470. queue.push(getLeftmost(list));
  73471. }
  73472. queue.sort(compareX);
  73473. // process holes from left to right
  73474. for (i = 0; i < queue.length; i++) {
  73475. eliminateHole(queue[i], outerNode);
  73476. outerNode = filterPoints(outerNode, outerNode.next);
  73477. }
  73478. return outerNode;
  73479. }
  73480. function compareX(a, b) {
  73481. return a.x - b.x;
  73482. }
  73483. // find a bridge between vertices that connects hole with an outer ring and and link it
  73484. function eliminateHole(hole, outerNode) {
  73485. outerNode = findHoleBridge(hole, outerNode);
  73486. if (outerNode) {
  73487. var b = splitPolygon(outerNode, hole);
  73488. filterPoints(b, b.next);
  73489. }
  73490. }
  73491. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73492. function findHoleBridge(hole, outerNode) {
  73493. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73494. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73495. // segment's endpoint with lesser x will be potential connection point
  73496. do {
  73497. if (hy <= p.y && hy >= p.next.y) {
  73498. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73499. if (x <= hx && x > qx) {
  73500. qx = x;
  73501. if (x === hx) {
  73502. if (hy === p.y)
  73503. return p;
  73504. if (hy === p.next.y)
  73505. return p.next;
  73506. }
  73507. m = p.x < p.next.x ? p : p.next;
  73508. }
  73509. }
  73510. p = p.next;
  73511. } while (p !== outerNode);
  73512. if (!m)
  73513. return null;
  73514. if (hx === qx)
  73515. return m.prev; // hole touches outer segment; pick lower endpoint
  73516. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73517. // if there are no points found, we have a valid connection;
  73518. // otherwise choose the point of the minimum angle with the ray as connection point
  73519. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73520. p = m.next;
  73521. while (p !== stop) {
  73522. if (hx >= p.x &&
  73523. p.x >= mx &&
  73524. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73525. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73526. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73527. m = p;
  73528. tanMin = tan;
  73529. }
  73530. }
  73531. p = p.next;
  73532. }
  73533. return m;
  73534. }
  73535. // interlink polygon nodes in z-order
  73536. function indexCurve(start, minX, minY, size) {
  73537. var p = start;
  73538. do {
  73539. if (p.z === null)
  73540. p.z = zOrder(p.x, p.y, minX, minY, size);
  73541. p.prevZ = p.prev;
  73542. p.nextZ = p.next;
  73543. p = p.next;
  73544. } while (p !== start);
  73545. p.prevZ.nextZ = null;
  73546. p.prevZ = null;
  73547. sortLinked(p);
  73548. }
  73549. // Simon Tatham's linked list merge sort algorithm
  73550. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73551. function sortLinked(list) {
  73552. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73553. do {
  73554. p = list;
  73555. list = null;
  73556. tail = null;
  73557. numMerges = 0;
  73558. while (p) {
  73559. numMerges++;
  73560. q = p;
  73561. pSize = 0;
  73562. for (i = 0; i < inSize; i++) {
  73563. pSize++;
  73564. q = q.nextZ;
  73565. if (!q)
  73566. break;
  73567. }
  73568. qSize = inSize;
  73569. while (pSize > 0 || (qSize > 0 && q)) {
  73570. if (pSize === 0) {
  73571. e = q;
  73572. q = q.nextZ;
  73573. qSize--;
  73574. }
  73575. else if (qSize === 0 || !q) {
  73576. e = p;
  73577. p = p.nextZ;
  73578. pSize--;
  73579. }
  73580. else if (p.z <= q.z) {
  73581. e = p;
  73582. p = p.nextZ;
  73583. pSize--;
  73584. }
  73585. else {
  73586. e = q;
  73587. q = q.nextZ;
  73588. qSize--;
  73589. }
  73590. if (tail)
  73591. tail.nextZ = e;
  73592. else
  73593. list = e;
  73594. e.prevZ = tail;
  73595. tail = e;
  73596. }
  73597. p = q;
  73598. }
  73599. tail.nextZ = null;
  73600. inSize *= 2;
  73601. } while (numMerges > 1);
  73602. return list;
  73603. }
  73604. // z-order of a point given coords and size of the data bounding box
  73605. function zOrder(x, y, minX, minY, size) {
  73606. // coords are transformed into non-negative 15-bit integer range
  73607. x = 32767 * (x - minX) / size;
  73608. y = 32767 * (y - minY) / size;
  73609. x = (x | (x << 8)) & 0x00FF00FF;
  73610. x = (x | (x << 4)) & 0x0F0F0F0F;
  73611. x = (x | (x << 2)) & 0x33333333;
  73612. x = (x | (x << 1)) & 0x55555555;
  73613. y = (y | (y << 8)) & 0x00FF00FF;
  73614. y = (y | (y << 4)) & 0x0F0F0F0F;
  73615. y = (y | (y << 2)) & 0x33333333;
  73616. y = (y | (y << 1)) & 0x55555555;
  73617. return x | (y << 1);
  73618. }
  73619. // find the leftmost node of a polygon ring
  73620. function getLeftmost(start) {
  73621. var p = start, leftmost = start;
  73622. do {
  73623. if (p.x < leftmost.x)
  73624. leftmost = p;
  73625. p = p.next;
  73626. } while (p !== start);
  73627. return leftmost;
  73628. }
  73629. // check if a point lies within a convex triangle
  73630. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73631. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73632. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73633. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73634. }
  73635. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73636. function isValidDiagonal(a, b) {
  73637. return a.next.i !== b.i &&
  73638. a.prev.i !== b.i &&
  73639. !intersectsPolygon(a, b) &&
  73640. locallyInside(a, b) &&
  73641. locallyInside(b, a) &&
  73642. middleInside(a, b);
  73643. }
  73644. // signed area of a triangle
  73645. function area(p, q, r) {
  73646. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73647. }
  73648. // check if two points are equal
  73649. function equals(p1, p2) {
  73650. return p1.x === p2.x && p1.y === p2.y;
  73651. }
  73652. // check if two segments intersect
  73653. function intersects(p1, q1, p2, q2) {
  73654. if ((equals(p1, q1) && equals(p2, q2)) ||
  73655. (equals(p1, q2) && equals(p2, q1)))
  73656. return true;
  73657. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73658. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73659. }
  73660. // check if a polygon diagonal intersects any polygon segments
  73661. function intersectsPolygon(a, b) {
  73662. var p = a;
  73663. do {
  73664. if (p.i !== a.i &&
  73665. p.next.i !== a.i &&
  73666. p.i !== b.i &&
  73667. p.next.i !== b.i &&
  73668. intersects(p, p.next, a, b))
  73669. return true;
  73670. p = p.next;
  73671. } while (p !== a);
  73672. return false;
  73673. }
  73674. // check if a polygon diagonal is locally inside the polygon
  73675. function locallyInside(a, b) {
  73676. return area(a.prev, a, a.next) < 0
  73677. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73678. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73679. }
  73680. // check if the middle point of a polygon diagonal is inside the polygon
  73681. function middleInside(a, b) {
  73682. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73683. do {
  73684. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73685. inside = !inside;
  73686. p = p.next;
  73687. } while (p !== a);
  73688. return inside;
  73689. }
  73690. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73691. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73692. function splitPolygon(a, b) {
  73693. 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;
  73694. a.next = b;
  73695. b.prev = a;
  73696. a2.next = an;
  73697. an.prev = a2;
  73698. b2.next = a2;
  73699. a2.prev = b2;
  73700. bp.next = b2;
  73701. b2.prev = bp;
  73702. return b2;
  73703. }
  73704. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73705. function insertNode(i, x, y, last) {
  73706. var p = new Node(i, x, y);
  73707. if (!last) {
  73708. p.prev = p;
  73709. p.next = p;
  73710. }
  73711. else {
  73712. p.next = last.next;
  73713. p.prev = last;
  73714. last.next.prev = p;
  73715. last.next = p;
  73716. }
  73717. return p;
  73718. }
  73719. function removeNode(p) {
  73720. p.next.prev = p.prev;
  73721. p.prev.next = p.next;
  73722. if (p.prevZ)
  73723. p.prevZ.nextZ = p.nextZ;
  73724. if (p.nextZ)
  73725. p.nextZ.prevZ = p.prevZ;
  73726. }
  73727. /**
  73728. * return a percentage difference between the polygon area and its triangulation area;
  73729. * used to verify correctness of triangulation
  73730. */
  73731. function deviation(data, holeIndices, dim, triangles) {
  73732. var hasHoles = holeIndices && holeIndices.length;
  73733. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73734. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73735. if (hasHoles) {
  73736. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73737. var start = holeIndices[i] * dim;
  73738. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73739. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73740. }
  73741. }
  73742. var trianglesArea = 0;
  73743. for (i = 0; i < triangles.length; i += 3) {
  73744. var a = triangles[i] * dim;
  73745. var b = triangles[i + 1] * dim;
  73746. var c = triangles[i + 2] * dim;
  73747. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73748. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73749. }
  73750. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73751. }
  73752. Earcut.deviation = deviation;
  73753. ;
  73754. function signedArea(data, start, end, dim) {
  73755. var sum = 0;
  73756. for (var i = start, j = end - dim; i < end; i += dim) {
  73757. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73758. j = i;
  73759. }
  73760. return sum;
  73761. }
  73762. /**
  73763. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73764. */
  73765. function flatten(data) {
  73766. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73767. for (var i = 0; i < data.length; i++) {
  73768. for (var j = 0; j < data[i].length; j++) {
  73769. for (var d = 0; d < dim; d++)
  73770. result.vertices.push(data[i][j][d]);
  73771. }
  73772. if (i > 0) {
  73773. holeIndex += data[i - 1].length;
  73774. result.holes.push(holeIndex);
  73775. }
  73776. }
  73777. return result;
  73778. }
  73779. Earcut.flatten = flatten;
  73780. ;
  73781. })(Earcut || (Earcut = {}));
  73782. //# sourceMappingURL=babylon.earcut.js.map
  73783. var BABYLON;
  73784. (function (BABYLON) {
  73785. var IndexedVector2 = /** @class */ (function (_super) {
  73786. __extends(IndexedVector2, _super);
  73787. function IndexedVector2(original, index) {
  73788. var _this = _super.call(this, original.x, original.y) || this;
  73789. _this.index = index;
  73790. return _this;
  73791. }
  73792. return IndexedVector2;
  73793. }(BABYLON.Vector2));
  73794. var PolygonPoints = /** @class */ (function () {
  73795. function PolygonPoints() {
  73796. this.elements = new Array();
  73797. }
  73798. PolygonPoints.prototype.add = function (originalPoints) {
  73799. var _this = this;
  73800. var result = new Array();
  73801. originalPoints.forEach(function (point) {
  73802. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73803. var newPoint = new IndexedVector2(point, _this.elements.length);
  73804. result.push(newPoint);
  73805. _this.elements.push(newPoint);
  73806. }
  73807. });
  73808. return result;
  73809. };
  73810. PolygonPoints.prototype.computeBounds = function () {
  73811. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73812. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73813. this.elements.forEach(function (point) {
  73814. // x
  73815. if (point.x < lmin.x) {
  73816. lmin.x = point.x;
  73817. }
  73818. else if (point.x > lmax.x) {
  73819. lmax.x = point.x;
  73820. }
  73821. // y
  73822. if (point.y < lmin.y) {
  73823. lmin.y = point.y;
  73824. }
  73825. else if (point.y > lmax.y) {
  73826. lmax.y = point.y;
  73827. }
  73828. });
  73829. return {
  73830. min: lmin,
  73831. max: lmax,
  73832. width: lmax.x - lmin.x,
  73833. height: lmax.y - lmin.y
  73834. };
  73835. };
  73836. return PolygonPoints;
  73837. }());
  73838. var Polygon = /** @class */ (function () {
  73839. function Polygon() {
  73840. }
  73841. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73842. return [
  73843. new BABYLON.Vector2(xmin, ymin),
  73844. new BABYLON.Vector2(xmax, ymin),
  73845. new BABYLON.Vector2(xmax, ymax),
  73846. new BABYLON.Vector2(xmin, ymax)
  73847. ];
  73848. };
  73849. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73850. if (cx === void 0) { cx = 0; }
  73851. if (cy === void 0) { cy = 0; }
  73852. if (numberOfSides === void 0) { numberOfSides = 32; }
  73853. var result = new Array();
  73854. var angle = 0;
  73855. var increment = (Math.PI * 2) / numberOfSides;
  73856. for (var i = 0; i < numberOfSides; i++) {
  73857. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73858. angle -= increment;
  73859. }
  73860. return result;
  73861. };
  73862. Polygon.Parse = function (input) {
  73863. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73864. var i, result = [];
  73865. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73866. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73867. }
  73868. return result;
  73869. };
  73870. Polygon.StartingAt = function (x, y) {
  73871. return BABYLON.Path2.StartingAt(x, y);
  73872. };
  73873. return Polygon;
  73874. }());
  73875. BABYLON.Polygon = Polygon;
  73876. var PolygonMeshBuilder = /** @class */ (function () {
  73877. function PolygonMeshBuilder(name, contours, scene) {
  73878. this._points = new PolygonPoints();
  73879. this._outlinepoints = new PolygonPoints();
  73880. this._holes = new Array();
  73881. this._epoints = new Array();
  73882. this._eholes = new Array();
  73883. this._name = name;
  73884. this._scene = scene;
  73885. var points;
  73886. if (contours instanceof BABYLON.Path2) {
  73887. points = contours.getPoints();
  73888. }
  73889. else {
  73890. points = contours;
  73891. }
  73892. this._addToepoint(points);
  73893. this._points.add(points);
  73894. this._outlinepoints.add(points);
  73895. }
  73896. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73897. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73898. var p = points_1[_i];
  73899. this._epoints.push(p.x, p.y);
  73900. }
  73901. };
  73902. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73903. this._points.add(hole);
  73904. var holepoints = new PolygonPoints();
  73905. holepoints.add(hole);
  73906. this._holes.push(holepoints);
  73907. this._eholes.push(this._epoints.length / 2);
  73908. this._addToepoint(hole);
  73909. return this;
  73910. };
  73911. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73912. var _this = this;
  73913. if (updatable === void 0) { updatable = false; }
  73914. if (depth === void 0) { depth = 0; }
  73915. var result = new BABYLON.Mesh(this._name, this._scene);
  73916. var normals = new Array();
  73917. var positions = new Array();
  73918. var uvs = new Array();
  73919. var bounds = this._points.computeBounds();
  73920. this._points.elements.forEach(function (p) {
  73921. normals.push(0, 1.0, 0);
  73922. positions.push(p.x, 0, p.y);
  73923. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73924. });
  73925. var indices = new Array();
  73926. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73927. for (var i = 0; i < res.length; i++) {
  73928. indices.push(res[i]);
  73929. }
  73930. if (depth > 0) {
  73931. var positionscount = (positions.length / 3); //get the current pointcount
  73932. this._points.elements.forEach(function (p) {
  73933. normals.push(0, -1.0, 0);
  73934. positions.push(p.x, -depth, p.y);
  73935. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73936. });
  73937. var totalCount = indices.length;
  73938. for (var i = 0; i < totalCount; i += 3) {
  73939. var i0 = indices[i + 0];
  73940. var i1 = indices[i + 1];
  73941. var i2 = indices[i + 2];
  73942. indices.push(i2 + positionscount);
  73943. indices.push(i1 + positionscount);
  73944. indices.push(i0 + positionscount);
  73945. }
  73946. //Add the sides
  73947. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73948. this._holes.forEach(function (hole) {
  73949. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73950. });
  73951. }
  73952. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73953. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73954. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73955. result.setIndices(indices);
  73956. return result;
  73957. };
  73958. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73959. var StartIndex = positions.length / 3;
  73960. var ulength = 0;
  73961. for (var i = 0; i < points.elements.length; i++) {
  73962. var p = points.elements[i];
  73963. var p1;
  73964. if ((i + 1) > points.elements.length - 1) {
  73965. p1 = points.elements[0];
  73966. }
  73967. else {
  73968. p1 = points.elements[i + 1];
  73969. }
  73970. positions.push(p.x, 0, p.y);
  73971. positions.push(p.x, -depth, p.y);
  73972. positions.push(p1.x, 0, p1.y);
  73973. positions.push(p1.x, -depth, p1.y);
  73974. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73975. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73976. var v3 = v2.subtract(v1);
  73977. var v4 = new BABYLON.Vector3(0, 1, 0);
  73978. var vn = BABYLON.Vector3.Cross(v3, v4);
  73979. vn = vn.normalize();
  73980. uvs.push(ulength / bounds.width, 0);
  73981. uvs.push(ulength / bounds.width, 1);
  73982. ulength += v3.length();
  73983. uvs.push((ulength / bounds.width), 0);
  73984. uvs.push((ulength / bounds.width), 1);
  73985. if (!flip) {
  73986. normals.push(-vn.x, -vn.y, -vn.z);
  73987. normals.push(-vn.x, -vn.y, -vn.z);
  73988. normals.push(-vn.x, -vn.y, -vn.z);
  73989. normals.push(-vn.x, -vn.y, -vn.z);
  73990. indices.push(StartIndex);
  73991. indices.push(StartIndex + 1);
  73992. indices.push(StartIndex + 2);
  73993. indices.push(StartIndex + 1);
  73994. indices.push(StartIndex + 3);
  73995. indices.push(StartIndex + 2);
  73996. }
  73997. else {
  73998. normals.push(vn.x, vn.y, vn.z);
  73999. normals.push(vn.x, vn.y, vn.z);
  74000. normals.push(vn.x, vn.y, vn.z);
  74001. normals.push(vn.x, vn.y, vn.z);
  74002. indices.push(StartIndex);
  74003. indices.push(StartIndex + 2);
  74004. indices.push(StartIndex + 1);
  74005. indices.push(StartIndex + 1);
  74006. indices.push(StartIndex + 2);
  74007. indices.push(StartIndex + 3);
  74008. }
  74009. StartIndex += 4;
  74010. }
  74011. ;
  74012. };
  74013. return PolygonMeshBuilder;
  74014. }());
  74015. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74016. })(BABYLON || (BABYLON = {}));
  74017. //# sourceMappingURL=babylon.polygonMesh.js.map
  74018. var BABYLON;
  74019. (function (BABYLON) {
  74020. // Unique ID when we import meshes from Babylon to CSG
  74021. var currentCSGMeshId = 0;
  74022. // # class Vertex
  74023. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74024. // one to provide additional features like texture coordinates and vertex
  74025. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74026. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74027. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74028. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74029. // is not used anywhere else.
  74030. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74031. var Vertex = /** @class */ (function () {
  74032. function Vertex(pos, normal, uv) {
  74033. this.pos = pos;
  74034. this.normal = normal;
  74035. this.uv = uv;
  74036. }
  74037. Vertex.prototype.clone = function () {
  74038. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74039. };
  74040. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74041. // orientation of a polygon is flipped.
  74042. Vertex.prototype.flip = function () {
  74043. this.normal = this.normal.scale(-1);
  74044. };
  74045. // Create a new vertex between this vertex and `other` by linearly
  74046. // interpolating all properties using a parameter of `t`. Subclasses should
  74047. // override this to interpolate additional properties.
  74048. Vertex.prototype.interpolate = function (other, t) {
  74049. 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));
  74050. };
  74051. return Vertex;
  74052. }());
  74053. // # class Plane
  74054. // Represents a plane in 3D space.
  74055. var Plane = /** @class */ (function () {
  74056. function Plane(normal, w) {
  74057. this.normal = normal;
  74058. this.w = w;
  74059. }
  74060. Plane.FromPoints = function (a, b, c) {
  74061. var v0 = c.subtract(a);
  74062. var v1 = b.subtract(a);
  74063. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74064. return null;
  74065. }
  74066. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74067. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74068. };
  74069. Plane.prototype.clone = function () {
  74070. return new Plane(this.normal.clone(), this.w);
  74071. };
  74072. Plane.prototype.flip = function () {
  74073. this.normal.scaleInPlace(-1);
  74074. this.w = -this.w;
  74075. };
  74076. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74077. // fragments in the appropriate lists. Coplanar polygons go into either
  74078. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74079. // respect to this plane. Polygons in front or in back of this plane go into
  74080. // either `front` or `back`.
  74081. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74082. var COPLANAR = 0;
  74083. var FRONT = 1;
  74084. var BACK = 2;
  74085. var SPANNING = 3;
  74086. // Classify each point as well as the entire polygon into one of the above
  74087. // four classes.
  74088. var polygonType = 0;
  74089. var types = [];
  74090. var i;
  74091. var t;
  74092. for (i = 0; i < polygon.vertices.length; i++) {
  74093. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74094. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74095. polygonType |= type;
  74096. types.push(type);
  74097. }
  74098. // Put the polygon in the correct list, splitting it when necessary.
  74099. switch (polygonType) {
  74100. case COPLANAR:
  74101. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74102. break;
  74103. case FRONT:
  74104. front.push(polygon);
  74105. break;
  74106. case BACK:
  74107. back.push(polygon);
  74108. break;
  74109. case SPANNING:
  74110. var f = [], b = [];
  74111. for (i = 0; i < polygon.vertices.length; i++) {
  74112. var j = (i + 1) % polygon.vertices.length;
  74113. var ti = types[i], tj = types[j];
  74114. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74115. if (ti !== BACK)
  74116. f.push(vi);
  74117. if (ti !== FRONT)
  74118. b.push(ti !== BACK ? vi.clone() : vi);
  74119. if ((ti | tj) === SPANNING) {
  74120. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74121. var v = vi.interpolate(vj, t);
  74122. f.push(v);
  74123. b.push(v.clone());
  74124. }
  74125. }
  74126. var poly;
  74127. if (f.length >= 3) {
  74128. poly = new Polygon(f, polygon.shared);
  74129. if (poly.plane)
  74130. front.push(poly);
  74131. }
  74132. if (b.length >= 3) {
  74133. poly = new Polygon(b, polygon.shared);
  74134. if (poly.plane)
  74135. back.push(poly);
  74136. }
  74137. break;
  74138. }
  74139. };
  74140. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74141. // point is on the plane.
  74142. Plane.EPSILON = 1e-5;
  74143. return Plane;
  74144. }());
  74145. // # class Polygon
  74146. // Represents a convex polygon. The vertices used to initialize a polygon must
  74147. // be coplanar and form a convex loop.
  74148. //
  74149. // Each convex polygon has a `shared` property, which is shared between all
  74150. // polygons that are clones of each other or were split from the same polygon.
  74151. // This can be used to define per-polygon properties (such as surface color).
  74152. var Polygon = /** @class */ (function () {
  74153. function Polygon(vertices, shared) {
  74154. this.vertices = vertices;
  74155. this.shared = shared;
  74156. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74157. }
  74158. Polygon.prototype.clone = function () {
  74159. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74160. return new Polygon(vertices, this.shared);
  74161. };
  74162. Polygon.prototype.flip = function () {
  74163. this.vertices.reverse().map(function (v) { v.flip(); });
  74164. this.plane.flip();
  74165. };
  74166. return Polygon;
  74167. }());
  74168. // # class Node
  74169. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74170. // by picking a polygon to split along. That polygon (and all other coplanar
  74171. // polygons) are added directly to that node and the other polygons are added to
  74172. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74173. // no distinction between internal and leaf nodes.
  74174. var Node = /** @class */ (function () {
  74175. function Node(polygons) {
  74176. this.plane = null;
  74177. this.front = null;
  74178. this.back = null;
  74179. this.polygons = new Array();
  74180. if (polygons) {
  74181. this.build(polygons);
  74182. }
  74183. }
  74184. Node.prototype.clone = function () {
  74185. var node = new Node();
  74186. node.plane = this.plane && this.plane.clone();
  74187. node.front = this.front && this.front.clone();
  74188. node.back = this.back && this.back.clone();
  74189. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74190. return node;
  74191. };
  74192. // Convert solid space to empty space and empty space to solid space.
  74193. Node.prototype.invert = function () {
  74194. for (var i = 0; i < this.polygons.length; i++) {
  74195. this.polygons[i].flip();
  74196. }
  74197. if (this.plane) {
  74198. this.plane.flip();
  74199. }
  74200. if (this.front) {
  74201. this.front.invert();
  74202. }
  74203. if (this.back) {
  74204. this.back.invert();
  74205. }
  74206. var temp = this.front;
  74207. this.front = this.back;
  74208. this.back = temp;
  74209. };
  74210. // Recursively remove all polygons in `polygons` that are inside this BSP
  74211. // tree.
  74212. Node.prototype.clipPolygons = function (polygons) {
  74213. if (!this.plane)
  74214. return polygons.slice();
  74215. var front = new Array(), back = new Array();
  74216. for (var i = 0; i < polygons.length; i++) {
  74217. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74218. }
  74219. if (this.front) {
  74220. front = this.front.clipPolygons(front);
  74221. }
  74222. if (this.back) {
  74223. back = this.back.clipPolygons(back);
  74224. }
  74225. else {
  74226. back = [];
  74227. }
  74228. return front.concat(back);
  74229. };
  74230. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74231. // `bsp`.
  74232. Node.prototype.clipTo = function (bsp) {
  74233. this.polygons = bsp.clipPolygons(this.polygons);
  74234. if (this.front)
  74235. this.front.clipTo(bsp);
  74236. if (this.back)
  74237. this.back.clipTo(bsp);
  74238. };
  74239. // Return a list of all polygons in this BSP tree.
  74240. Node.prototype.allPolygons = function () {
  74241. var polygons = this.polygons.slice();
  74242. if (this.front)
  74243. polygons = polygons.concat(this.front.allPolygons());
  74244. if (this.back)
  74245. polygons = polygons.concat(this.back.allPolygons());
  74246. return polygons;
  74247. };
  74248. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74249. // new polygons are filtered down to the bottom of the tree and become new
  74250. // nodes there. Each set of polygons is partitioned using the first polygon
  74251. // (no heuristic is used to pick a good split).
  74252. Node.prototype.build = function (polygons) {
  74253. if (!polygons.length)
  74254. return;
  74255. if (!this.plane)
  74256. this.plane = polygons[0].plane.clone();
  74257. var front = new Array(), back = new Array();
  74258. for (var i = 0; i < polygons.length; i++) {
  74259. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74260. }
  74261. if (front.length) {
  74262. if (!this.front)
  74263. this.front = new Node();
  74264. this.front.build(front);
  74265. }
  74266. if (back.length) {
  74267. if (!this.back)
  74268. this.back = new Node();
  74269. this.back.build(back);
  74270. }
  74271. };
  74272. return Node;
  74273. }());
  74274. var CSG = /** @class */ (function () {
  74275. function CSG() {
  74276. this.polygons = new Array();
  74277. }
  74278. // Convert BABYLON.Mesh to BABYLON.CSG
  74279. CSG.FromMesh = function (mesh) {
  74280. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74281. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74282. if (mesh instanceof BABYLON.Mesh) {
  74283. mesh.computeWorldMatrix(true);
  74284. matrix = mesh.getWorldMatrix();
  74285. meshPosition = mesh.position.clone();
  74286. meshRotation = mesh.rotation.clone();
  74287. if (mesh.rotationQuaternion) {
  74288. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74289. }
  74290. meshScaling = mesh.scaling.clone();
  74291. }
  74292. else {
  74293. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74294. }
  74295. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74296. var subMeshes = mesh.subMeshes;
  74297. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74298. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74299. vertices = [];
  74300. for (var j = 0; j < 3; j++) {
  74301. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74302. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74303. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74304. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74305. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74306. vertex = new Vertex(position, normal, uv);
  74307. vertices.push(vertex);
  74308. }
  74309. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74310. // To handle the case of degenerated triangle
  74311. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74312. if (polygon.plane)
  74313. polygons.push(polygon);
  74314. }
  74315. }
  74316. var csg = CSG.FromPolygons(polygons);
  74317. csg.matrix = matrix;
  74318. csg.position = meshPosition;
  74319. csg.rotation = meshRotation;
  74320. csg.scaling = meshScaling;
  74321. csg.rotationQuaternion = meshRotationQuaternion;
  74322. currentCSGMeshId++;
  74323. return csg;
  74324. };
  74325. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74326. CSG.FromPolygons = function (polygons) {
  74327. var csg = new CSG();
  74328. csg.polygons = polygons;
  74329. return csg;
  74330. };
  74331. CSG.prototype.clone = function () {
  74332. var csg = new CSG();
  74333. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74334. csg.copyTransformAttributes(this);
  74335. return csg;
  74336. };
  74337. CSG.prototype.union = function (csg) {
  74338. var a = new Node(this.clone().polygons);
  74339. var b = new Node(csg.clone().polygons);
  74340. a.clipTo(b);
  74341. b.clipTo(a);
  74342. b.invert();
  74343. b.clipTo(a);
  74344. b.invert();
  74345. a.build(b.allPolygons());
  74346. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74347. };
  74348. CSG.prototype.unionInPlace = function (csg) {
  74349. var a = new Node(this.polygons);
  74350. var b = new Node(csg.polygons);
  74351. a.clipTo(b);
  74352. b.clipTo(a);
  74353. b.invert();
  74354. b.clipTo(a);
  74355. b.invert();
  74356. a.build(b.allPolygons());
  74357. this.polygons = a.allPolygons();
  74358. };
  74359. CSG.prototype.subtract = function (csg) {
  74360. var a = new Node(this.clone().polygons);
  74361. var b = new Node(csg.clone().polygons);
  74362. a.invert();
  74363. a.clipTo(b);
  74364. b.clipTo(a);
  74365. b.invert();
  74366. b.clipTo(a);
  74367. b.invert();
  74368. a.build(b.allPolygons());
  74369. a.invert();
  74370. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74371. };
  74372. CSG.prototype.subtractInPlace = function (csg) {
  74373. var a = new Node(this.polygons);
  74374. var b = new Node(csg.polygons);
  74375. a.invert();
  74376. a.clipTo(b);
  74377. b.clipTo(a);
  74378. b.invert();
  74379. b.clipTo(a);
  74380. b.invert();
  74381. a.build(b.allPolygons());
  74382. a.invert();
  74383. this.polygons = a.allPolygons();
  74384. };
  74385. CSG.prototype.intersect = function (csg) {
  74386. var a = new Node(this.clone().polygons);
  74387. var b = new Node(csg.clone().polygons);
  74388. a.invert();
  74389. b.clipTo(a);
  74390. b.invert();
  74391. a.clipTo(b);
  74392. b.clipTo(a);
  74393. a.build(b.allPolygons());
  74394. a.invert();
  74395. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74396. };
  74397. CSG.prototype.intersectInPlace = function (csg) {
  74398. var a = new Node(this.polygons);
  74399. var b = new Node(csg.polygons);
  74400. a.invert();
  74401. b.clipTo(a);
  74402. b.invert();
  74403. a.clipTo(b);
  74404. b.clipTo(a);
  74405. a.build(b.allPolygons());
  74406. a.invert();
  74407. this.polygons = a.allPolygons();
  74408. };
  74409. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74410. // not modified.
  74411. CSG.prototype.inverse = function () {
  74412. var csg = this.clone();
  74413. csg.inverseInPlace();
  74414. return csg;
  74415. };
  74416. CSG.prototype.inverseInPlace = function () {
  74417. this.polygons.map(function (p) { p.flip(); });
  74418. };
  74419. // This is used to keep meshes transformations so they can be restored
  74420. // when we build back a Babylon Mesh
  74421. // NB : All CSG operations are performed in world coordinates
  74422. CSG.prototype.copyTransformAttributes = function (csg) {
  74423. this.matrix = csg.matrix;
  74424. this.position = csg.position;
  74425. this.rotation = csg.rotation;
  74426. this.scaling = csg.scaling;
  74427. this.rotationQuaternion = csg.rotationQuaternion;
  74428. return this;
  74429. };
  74430. // Build Raw mesh from CSG
  74431. // Coordinates here are in world space
  74432. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74433. var matrix = this.matrix.clone();
  74434. matrix.invert();
  74435. 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;
  74436. if (keepSubMeshes) {
  74437. // Sort Polygons, since subMeshes are indices range
  74438. polygons.sort(function (a, b) {
  74439. if (a.shared.meshId === b.shared.meshId) {
  74440. return a.shared.subMeshId - b.shared.subMeshId;
  74441. }
  74442. else {
  74443. return a.shared.meshId - b.shared.meshId;
  74444. }
  74445. });
  74446. }
  74447. for (var i = 0, il = polygons.length; i < il; i++) {
  74448. polygon = polygons[i];
  74449. // Building SubMeshes
  74450. if (!subMesh_dict[polygon.shared.meshId]) {
  74451. subMesh_dict[polygon.shared.meshId] = {};
  74452. }
  74453. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74454. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74455. indexStart: +Infinity,
  74456. indexEnd: -Infinity,
  74457. materialIndex: polygon.shared.materialIndex
  74458. };
  74459. }
  74460. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74461. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74462. polygonIndices[0] = 0;
  74463. polygonIndices[1] = j - 1;
  74464. polygonIndices[2] = j;
  74465. for (var k = 0; k < 3; k++) {
  74466. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74467. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74468. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74469. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74470. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74471. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74472. // Check if 2 points can be merged
  74473. if (!(typeof vertex_idx !== 'undefined' &&
  74474. normals[vertex_idx * 3] === localNormal.x &&
  74475. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74476. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74477. uvs[vertex_idx * 2] === uv.x &&
  74478. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74479. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74480. uvs.push(uv.x, uv.y);
  74481. normals.push(normal.x, normal.y, normal.z);
  74482. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74483. }
  74484. indices.push(vertex_idx);
  74485. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74486. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74487. currentIndex++;
  74488. }
  74489. }
  74490. }
  74491. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74492. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74493. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74494. mesh.setIndices(indices, null);
  74495. if (keepSubMeshes) {
  74496. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74497. var materialIndexOffset = 0, materialMaxIndex;
  74498. mesh.subMeshes = new Array();
  74499. for (var m in subMesh_dict) {
  74500. materialMaxIndex = -1;
  74501. for (var sm in subMesh_dict[m]) {
  74502. subMesh_obj = subMesh_dict[m][sm];
  74503. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74504. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74505. }
  74506. materialIndexOffset += ++materialMaxIndex;
  74507. }
  74508. }
  74509. return mesh;
  74510. };
  74511. // Build Mesh from CSG taking material and transforms into account
  74512. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74513. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74514. mesh.material = material;
  74515. mesh.position.copyFrom(this.position);
  74516. mesh.rotation.copyFrom(this.rotation);
  74517. if (this.rotationQuaternion) {
  74518. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74519. }
  74520. mesh.scaling.copyFrom(this.scaling);
  74521. mesh.computeWorldMatrix(true);
  74522. return mesh;
  74523. };
  74524. return CSG;
  74525. }());
  74526. BABYLON.CSG = CSG;
  74527. })(BABYLON || (BABYLON = {}));
  74528. //# sourceMappingURL=babylon.csg.js.map
  74529. var BABYLON;
  74530. (function (BABYLON) {
  74531. var LensFlare = /** @class */ (function () {
  74532. function LensFlare(size, position, color, imgUrl, system) {
  74533. this.size = size;
  74534. this.position = position;
  74535. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74536. this.color = color || new BABYLON.Color3(1, 1, 1);
  74537. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74538. this._system = system;
  74539. system.lensFlares.push(this);
  74540. }
  74541. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74542. return new LensFlare(size, position, color, imgUrl, system);
  74543. };
  74544. LensFlare.prototype.dispose = function () {
  74545. if (this.texture) {
  74546. this.texture.dispose();
  74547. }
  74548. // Remove from scene
  74549. var index = this._system.lensFlares.indexOf(this);
  74550. this._system.lensFlares.splice(index, 1);
  74551. };
  74552. ;
  74553. return LensFlare;
  74554. }());
  74555. BABYLON.LensFlare = LensFlare;
  74556. })(BABYLON || (BABYLON = {}));
  74557. //# sourceMappingURL=babylon.lensFlare.js.map
  74558. var BABYLON;
  74559. (function (BABYLON) {
  74560. var LensFlareSystem = /** @class */ (function () {
  74561. function LensFlareSystem(name, emitter, scene) {
  74562. this.name = name;
  74563. this.lensFlares = new Array();
  74564. this.borderLimit = 300;
  74565. this.viewportBorder = 0;
  74566. this.layerMask = 0x0FFFFFFF;
  74567. this._vertexBuffers = {};
  74568. this._isEnabled = true;
  74569. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74570. this._emitter = emitter;
  74571. this.id = name;
  74572. scene.lensFlareSystems.push(this);
  74573. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74574. var engine = scene.getEngine();
  74575. // VBO
  74576. var vertices = [];
  74577. vertices.push(1, 1);
  74578. vertices.push(-1, 1);
  74579. vertices.push(-1, -1);
  74580. vertices.push(1, -1);
  74581. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74582. // Indices
  74583. var indices = [];
  74584. indices.push(0);
  74585. indices.push(1);
  74586. indices.push(2);
  74587. indices.push(0);
  74588. indices.push(2);
  74589. indices.push(3);
  74590. this._indexBuffer = engine.createIndexBuffer(indices);
  74591. // Effects
  74592. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74593. }
  74594. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74595. get: function () {
  74596. return this._isEnabled;
  74597. },
  74598. set: function (value) {
  74599. this._isEnabled = value;
  74600. },
  74601. enumerable: true,
  74602. configurable: true
  74603. });
  74604. LensFlareSystem.prototype.getScene = function () {
  74605. return this._scene;
  74606. };
  74607. LensFlareSystem.prototype.getEmitter = function () {
  74608. return this._emitter;
  74609. };
  74610. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74611. this._emitter = newEmitter;
  74612. };
  74613. LensFlareSystem.prototype.getEmitterPosition = function () {
  74614. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74615. };
  74616. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74617. var position = this.getEmitterPosition();
  74618. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74619. this._positionX = position.x;
  74620. this._positionY = position.y;
  74621. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74622. if (this.viewportBorder > 0) {
  74623. globalViewport.x -= this.viewportBorder;
  74624. globalViewport.y -= this.viewportBorder;
  74625. globalViewport.width += this.viewportBorder * 2;
  74626. globalViewport.height += this.viewportBorder * 2;
  74627. position.x += this.viewportBorder;
  74628. position.y += this.viewportBorder;
  74629. this._positionX += this.viewportBorder;
  74630. this._positionY += this.viewportBorder;
  74631. }
  74632. if (position.z > 0) {
  74633. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74634. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74635. return true;
  74636. }
  74637. return true;
  74638. }
  74639. return false;
  74640. };
  74641. LensFlareSystem.prototype._isVisible = function () {
  74642. if (!this._isEnabled || !this._scene.activeCamera) {
  74643. return false;
  74644. }
  74645. var emitterPosition = this.getEmitterPosition();
  74646. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74647. var distance = direction.length();
  74648. direction.normalize();
  74649. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74650. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74651. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74652. };
  74653. LensFlareSystem.prototype.render = function () {
  74654. if (!this._effect.isReady() || !this._scene.activeCamera)
  74655. return false;
  74656. var engine = this._scene.getEngine();
  74657. var viewport = this._scene.activeCamera.viewport;
  74658. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74659. // Position
  74660. if (!this.computeEffectivePosition(globalViewport)) {
  74661. return false;
  74662. }
  74663. // Visibility
  74664. if (!this._isVisible()) {
  74665. return false;
  74666. }
  74667. // Intensity
  74668. var awayX;
  74669. var awayY;
  74670. if (this._positionX < this.borderLimit + globalViewport.x) {
  74671. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74672. }
  74673. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74674. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74675. }
  74676. else {
  74677. awayX = 0;
  74678. }
  74679. if (this._positionY < this.borderLimit + globalViewport.y) {
  74680. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74681. }
  74682. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74683. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74684. }
  74685. else {
  74686. awayY = 0;
  74687. }
  74688. var away = (awayX > awayY) ? awayX : awayY;
  74689. away -= this.viewportBorder;
  74690. if (away > this.borderLimit) {
  74691. away = this.borderLimit;
  74692. }
  74693. var intensity = 1.0 - (away / this.borderLimit);
  74694. if (intensity < 0) {
  74695. return false;
  74696. }
  74697. if (intensity > 1.0) {
  74698. intensity = 1.0;
  74699. }
  74700. if (this.viewportBorder > 0) {
  74701. globalViewport.x += this.viewportBorder;
  74702. globalViewport.y += this.viewportBorder;
  74703. globalViewport.width -= this.viewportBorder * 2;
  74704. globalViewport.height -= this.viewportBorder * 2;
  74705. this._positionX -= this.viewportBorder;
  74706. this._positionY -= this.viewportBorder;
  74707. }
  74708. // Position
  74709. var centerX = globalViewport.x + globalViewport.width / 2;
  74710. var centerY = globalViewport.y + globalViewport.height / 2;
  74711. var distX = centerX - this._positionX;
  74712. var distY = centerY - this._positionY;
  74713. // Effects
  74714. engine.enableEffect(this._effect);
  74715. engine.setState(false);
  74716. engine.setDepthBuffer(false);
  74717. // VBOs
  74718. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74719. // Flares
  74720. for (var index = 0; index < this.lensFlares.length; index++) {
  74721. var flare = this.lensFlares[index];
  74722. engine.setAlphaMode(flare.alphaMode);
  74723. var x = centerX - (distX * flare.position);
  74724. var y = centerY - (distY * flare.position);
  74725. var cw = flare.size;
  74726. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74727. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74728. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74729. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74730. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74731. // Texture
  74732. this._effect.setTexture("textureSampler", flare.texture);
  74733. // Color
  74734. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74735. // Draw order
  74736. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74737. }
  74738. engine.setDepthBuffer(true);
  74739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74740. return true;
  74741. };
  74742. LensFlareSystem.prototype.dispose = function () {
  74743. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74744. if (vertexBuffer) {
  74745. vertexBuffer.dispose();
  74746. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74747. }
  74748. if (this._indexBuffer) {
  74749. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74750. this._indexBuffer = null;
  74751. }
  74752. while (this.lensFlares.length) {
  74753. this.lensFlares[0].dispose();
  74754. }
  74755. // Remove from scene
  74756. var index = this._scene.lensFlareSystems.indexOf(this);
  74757. this._scene.lensFlareSystems.splice(index, 1);
  74758. };
  74759. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74760. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74761. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74762. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74763. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74764. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74765. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74766. var parsedFlare = parsedLensFlareSystem.flares[index];
  74767. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74768. }
  74769. return lensFlareSystem;
  74770. };
  74771. LensFlareSystem.prototype.serialize = function () {
  74772. var serializationObject = {};
  74773. serializationObject.id = this.id;
  74774. serializationObject.name = this.name;
  74775. serializationObject.emitterId = this.getEmitter().id;
  74776. serializationObject.borderLimit = this.borderLimit;
  74777. serializationObject.flares = [];
  74778. for (var index = 0; index < this.lensFlares.length; index++) {
  74779. var flare = this.lensFlares[index];
  74780. serializationObject.flares.push({
  74781. size: flare.size,
  74782. position: flare.position,
  74783. color: flare.color.asArray(),
  74784. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74785. });
  74786. }
  74787. return serializationObject;
  74788. };
  74789. return LensFlareSystem;
  74790. }());
  74791. BABYLON.LensFlareSystem = LensFlareSystem;
  74792. })(BABYLON || (BABYLON = {}));
  74793. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74794. var BABYLON;
  74795. (function (BABYLON) {
  74796. /**
  74797. * This is a holder class for the physics joint created by the physics plugin.
  74798. * It holds a set of functions to control the underlying joint.
  74799. */
  74800. var PhysicsJoint = /** @class */ (function () {
  74801. function PhysicsJoint(type, jointData) {
  74802. this.type = type;
  74803. this.jointData = jointData;
  74804. jointData.nativeParams = jointData.nativeParams || {};
  74805. }
  74806. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74807. get: function () {
  74808. return this._physicsJoint;
  74809. },
  74810. set: function (newJoint) {
  74811. if (this._physicsJoint) {
  74812. //remove from the wolrd
  74813. }
  74814. this._physicsJoint = newJoint;
  74815. },
  74816. enumerable: true,
  74817. configurable: true
  74818. });
  74819. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74820. set: function (physicsPlugin) {
  74821. this._physicsPlugin = physicsPlugin;
  74822. },
  74823. enumerable: true,
  74824. configurable: true
  74825. });
  74826. /**
  74827. * Execute a function that is physics-plugin specific.
  74828. * @param {Function} func the function that will be executed.
  74829. * It accepts two parameters: the physics world and the physics joint.
  74830. */
  74831. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74832. func(this._physicsPlugin.world, this._physicsJoint);
  74833. };
  74834. //TODO check if the native joints are the same
  74835. //Joint Types
  74836. PhysicsJoint.DistanceJoint = 0;
  74837. PhysicsJoint.HingeJoint = 1;
  74838. PhysicsJoint.BallAndSocketJoint = 2;
  74839. PhysicsJoint.WheelJoint = 3;
  74840. PhysicsJoint.SliderJoint = 4;
  74841. //OIMO
  74842. PhysicsJoint.PrismaticJoint = 5;
  74843. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74844. PhysicsJoint.UniversalJoint = 6;
  74845. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74846. //Cannon
  74847. //Similar to a Ball-Joint. Different in params
  74848. PhysicsJoint.PointToPointJoint = 8;
  74849. //Cannon only at the moment
  74850. PhysicsJoint.SpringJoint = 9;
  74851. PhysicsJoint.LockJoint = 10;
  74852. return PhysicsJoint;
  74853. }());
  74854. BABYLON.PhysicsJoint = PhysicsJoint;
  74855. /**
  74856. * A class representing a physics distance joint.
  74857. */
  74858. var DistanceJoint = /** @class */ (function (_super) {
  74859. __extends(DistanceJoint, _super);
  74860. function DistanceJoint(jointData) {
  74861. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74862. }
  74863. /**
  74864. * Update the predefined distance.
  74865. */
  74866. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74867. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74868. };
  74869. return DistanceJoint;
  74870. }(PhysicsJoint));
  74871. BABYLON.DistanceJoint = DistanceJoint;
  74872. var MotorEnabledJoint = /** @class */ (function (_super) {
  74873. __extends(MotorEnabledJoint, _super);
  74874. function MotorEnabledJoint(type, jointData) {
  74875. return _super.call(this, type, jointData) || this;
  74876. }
  74877. /**
  74878. * Set the motor values.
  74879. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74880. * @param {number} force the force to apply
  74881. * @param {number} maxForce max force for this motor.
  74882. */
  74883. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74884. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74885. };
  74886. /**
  74887. * Set the motor's limits.
  74888. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74889. */
  74890. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74891. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74892. };
  74893. return MotorEnabledJoint;
  74894. }(PhysicsJoint));
  74895. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74896. /**
  74897. * This class represents a single hinge physics joint
  74898. */
  74899. var HingeJoint = /** @class */ (function (_super) {
  74900. __extends(HingeJoint, _super);
  74901. function HingeJoint(jointData) {
  74902. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74903. }
  74904. /**
  74905. * Set the motor values.
  74906. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74907. * @param {number} force the force to apply
  74908. * @param {number} maxForce max force for this motor.
  74909. */
  74910. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74911. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74912. };
  74913. /**
  74914. * Set the motor's limits.
  74915. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74916. */
  74917. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74918. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74919. };
  74920. return HingeJoint;
  74921. }(MotorEnabledJoint));
  74922. BABYLON.HingeJoint = HingeJoint;
  74923. /**
  74924. * This class represents a dual hinge physics joint (same as wheel joint)
  74925. */
  74926. var Hinge2Joint = /** @class */ (function (_super) {
  74927. __extends(Hinge2Joint, _super);
  74928. function Hinge2Joint(jointData) {
  74929. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74930. }
  74931. /**
  74932. * Set the motor values.
  74933. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74934. * @param {number} force the force to apply
  74935. * @param {number} maxForce max force for this motor.
  74936. * @param {motorIndex} the motor's index, 0 or 1.
  74937. */
  74938. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74939. if (motorIndex === void 0) { motorIndex = 0; }
  74940. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74941. };
  74942. /**
  74943. * Set the motor limits.
  74944. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74945. * @param {number} upperLimit the upper limit
  74946. * @param {number} lowerLimit lower limit
  74947. * @param {motorIndex} the motor's index, 0 or 1.
  74948. */
  74949. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74950. if (motorIndex === void 0) { motorIndex = 0; }
  74951. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74952. };
  74953. return Hinge2Joint;
  74954. }(MotorEnabledJoint));
  74955. BABYLON.Hinge2Joint = Hinge2Joint;
  74956. })(BABYLON || (BABYLON = {}));
  74957. //# sourceMappingURL=babylon.physicsJoint.js.map
  74958. var BABYLON;
  74959. (function (BABYLON) {
  74960. var PhysicsImpostor = /** @class */ (function () {
  74961. function PhysicsImpostor(object, type, _options, _scene) {
  74962. if (_options === void 0) { _options = { mass: 0 }; }
  74963. var _this = this;
  74964. this.object = object;
  74965. this.type = type;
  74966. this._options = _options;
  74967. this._scene = _scene;
  74968. this._bodyUpdateRequired = false;
  74969. this._onBeforePhysicsStepCallbacks = new Array();
  74970. this._onAfterPhysicsStepCallbacks = new Array();
  74971. this._onPhysicsCollideCallbacks = [];
  74972. this._deltaPosition = BABYLON.Vector3.Zero();
  74973. this._isDisposed = false;
  74974. //temp variables for parent rotation calculations
  74975. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74976. this._tmpQuat = new BABYLON.Quaternion();
  74977. this._tmpQuat2 = new BABYLON.Quaternion();
  74978. /**
  74979. * this function is executed by the physics engine.
  74980. */
  74981. this.beforeStep = function () {
  74982. if (!_this._physicsEngine) {
  74983. return;
  74984. }
  74985. _this.object.translate(_this._deltaPosition, -1);
  74986. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74987. _this.object.computeWorldMatrix(false);
  74988. if (_this.object.parent && _this.object.rotationQuaternion) {
  74989. _this.getParentsRotation();
  74990. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74991. }
  74992. else {
  74993. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74994. }
  74995. if (!_this._options.disableBidirectionalTransformation) {
  74996. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74997. }
  74998. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74999. func(_this);
  75000. });
  75001. };
  75002. /**
  75003. * this function is executed by the physics engine.
  75004. */
  75005. this.afterStep = function () {
  75006. if (!_this._physicsEngine) {
  75007. return;
  75008. }
  75009. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75010. func(_this);
  75011. });
  75012. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75013. // object has now its world rotation. needs to be converted to local.
  75014. if (_this.object.parent && _this.object.rotationQuaternion) {
  75015. _this.getParentsRotation();
  75016. _this._tmpQuat.conjugateInPlace();
  75017. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75018. }
  75019. // take the position set and make it the absolute position of this object.
  75020. _this.object.setAbsolutePosition(_this.object.position);
  75021. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75022. _this.object.translate(_this._deltaPosition, 1);
  75023. };
  75024. /**
  75025. * Legacy collision detection event support
  75026. */
  75027. this.onCollideEvent = null;
  75028. //event and body object due to cannon's event-based architecture.
  75029. this.onCollide = function (e) {
  75030. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75031. return;
  75032. }
  75033. if (!_this._physicsEngine) {
  75034. return;
  75035. }
  75036. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75037. if (otherImpostor) {
  75038. // Legacy collision detection event support
  75039. if (_this.onCollideEvent) {
  75040. _this.onCollideEvent(_this, otherImpostor);
  75041. }
  75042. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75043. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75044. }).forEach(function (obj) {
  75045. obj.callback(_this, otherImpostor);
  75046. });
  75047. }
  75048. };
  75049. //sanity check!
  75050. if (!this.object) {
  75051. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75052. return;
  75053. }
  75054. //legacy support for old syntax.
  75055. if (!this._scene && object.getScene) {
  75056. this._scene = object.getScene();
  75057. }
  75058. if (!this._scene) {
  75059. return;
  75060. }
  75061. this._physicsEngine = this._scene.getPhysicsEngine();
  75062. if (!this._physicsEngine) {
  75063. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75064. }
  75065. else {
  75066. //set the object's quaternion, if not set
  75067. if (!this.object.rotationQuaternion) {
  75068. if (this.object.rotation) {
  75069. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75070. }
  75071. else {
  75072. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75073. }
  75074. }
  75075. //default options params
  75076. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75077. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75078. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75079. this._joints = [];
  75080. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75081. if (!this.object.parent || this._options.ignoreParent) {
  75082. this._init();
  75083. }
  75084. else if (this.object.parent.physicsImpostor) {
  75085. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75086. }
  75087. }
  75088. }
  75089. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75090. get: function () {
  75091. return this._isDisposed;
  75092. },
  75093. enumerable: true,
  75094. configurable: true
  75095. });
  75096. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75097. get: function () {
  75098. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75099. },
  75100. set: function (value) {
  75101. this.setMass(value);
  75102. },
  75103. enumerable: true,
  75104. configurable: true
  75105. });
  75106. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75107. get: function () {
  75108. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75109. },
  75110. set: function (value) {
  75111. if (!this._physicsEngine) {
  75112. return;
  75113. }
  75114. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75115. },
  75116. enumerable: true,
  75117. configurable: true
  75118. });
  75119. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75120. get: function () {
  75121. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75122. },
  75123. set: function (value) {
  75124. if (!this._physicsEngine) {
  75125. return;
  75126. }
  75127. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75128. },
  75129. enumerable: true,
  75130. configurable: true
  75131. });
  75132. /**
  75133. * This function will completly initialize this impostor.
  75134. * It will create a new body - but only if this mesh has no parent.
  75135. * If it has, this impostor will not be used other than to define the impostor
  75136. * of the child mesh.
  75137. */
  75138. PhysicsImpostor.prototype._init = function () {
  75139. if (!this._physicsEngine) {
  75140. return;
  75141. }
  75142. this._physicsEngine.removeImpostor(this);
  75143. this.physicsBody = null;
  75144. this._parent = this._parent || this._getPhysicsParent();
  75145. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75146. this._physicsEngine.addImpostor(this);
  75147. }
  75148. };
  75149. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75150. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75151. var parentMesh = this.object.parent;
  75152. return parentMesh.physicsImpostor;
  75153. }
  75154. return null;
  75155. };
  75156. /**
  75157. * Should a new body be generated.
  75158. */
  75159. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75160. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75161. };
  75162. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75163. this.forceUpdate();
  75164. };
  75165. /**
  75166. * Force a regeneration of this or the parent's impostor's body.
  75167. * Use under cautious - This will remove all joints already implemented.
  75168. */
  75169. PhysicsImpostor.prototype.forceUpdate = function () {
  75170. this._init();
  75171. if (this.parent && !this._options.ignoreParent) {
  75172. this.parent.forceUpdate();
  75173. }
  75174. };
  75175. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75176. /*public get mesh(): AbstractMesh {
  75177. return this._mesh;
  75178. }*/
  75179. /**
  75180. * Gets the body that holds this impostor. Either its own, or its parent.
  75181. */
  75182. get: function () {
  75183. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75184. },
  75185. /**
  75186. * Set the physics body. Used mainly by the physics engine/plugin
  75187. */
  75188. set: function (physicsBody) {
  75189. if (this._physicsBody && this._physicsEngine) {
  75190. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75191. }
  75192. this._physicsBody = physicsBody;
  75193. this.resetUpdateFlags();
  75194. },
  75195. enumerable: true,
  75196. configurable: true
  75197. });
  75198. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75199. get: function () {
  75200. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75201. },
  75202. set: function (value) {
  75203. this._parent = value;
  75204. },
  75205. enumerable: true,
  75206. configurable: true
  75207. });
  75208. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75209. this._bodyUpdateRequired = false;
  75210. };
  75211. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75212. if (this.object.getBoundingInfo) {
  75213. var q = this.object.rotationQuaternion;
  75214. //reset rotation
  75215. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75216. //calculate the world matrix with no rotation
  75217. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75218. var boundingInfo = this.object.getBoundingInfo();
  75219. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75220. //bring back the rotation
  75221. this.object.rotationQuaternion = q;
  75222. //calculate the world matrix with the new rotation
  75223. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75224. return size;
  75225. }
  75226. else {
  75227. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75228. }
  75229. };
  75230. PhysicsImpostor.prototype.getObjectCenter = function () {
  75231. if (this.object.getBoundingInfo) {
  75232. var boundingInfo = this.object.getBoundingInfo();
  75233. return boundingInfo.boundingBox.centerWorld;
  75234. }
  75235. else {
  75236. return this.object.position;
  75237. }
  75238. };
  75239. /**
  75240. * Get a specific parametes from the options parameter.
  75241. */
  75242. PhysicsImpostor.prototype.getParam = function (paramName) {
  75243. return this._options[paramName];
  75244. };
  75245. /**
  75246. * Sets a specific parameter in the options given to the physics plugin
  75247. */
  75248. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75249. this._options[paramName] = value;
  75250. this._bodyUpdateRequired = true;
  75251. };
  75252. /**
  75253. * Specifically change the body's mass option. Won't recreate the physics body object
  75254. */
  75255. PhysicsImpostor.prototype.setMass = function (mass) {
  75256. if (this.getParam("mass") !== mass) {
  75257. this.setParam("mass", mass);
  75258. }
  75259. if (this._physicsEngine) {
  75260. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75261. }
  75262. };
  75263. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75264. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75265. };
  75266. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75267. if (this._physicsEngine) {
  75268. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75269. }
  75270. };
  75271. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75272. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75273. };
  75274. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75275. if (this._physicsEngine) {
  75276. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75277. }
  75278. };
  75279. /**
  75280. * Execute a function with the physics plugin native code.
  75281. * Provide a function the will have two variables - the world object and the physics body object.
  75282. */
  75283. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75284. if (this._physicsEngine) {
  75285. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75286. }
  75287. };
  75288. /**
  75289. * Register a function that will be executed before the physics world is stepping forward.
  75290. */
  75291. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75292. this._onBeforePhysicsStepCallbacks.push(func);
  75293. };
  75294. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75295. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75296. if (index > -1) {
  75297. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75298. }
  75299. else {
  75300. BABYLON.Tools.Warn("Function to remove was not found");
  75301. }
  75302. };
  75303. /**
  75304. * Register a function that will be executed after the physics step
  75305. */
  75306. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75307. this._onAfterPhysicsStepCallbacks.push(func);
  75308. };
  75309. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75310. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75311. if (index > -1) {
  75312. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75313. }
  75314. else {
  75315. BABYLON.Tools.Warn("Function to remove was not found");
  75316. }
  75317. };
  75318. /**
  75319. * register a function that will be executed when this impostor collides against a different body.
  75320. */
  75321. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75322. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75323. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75324. };
  75325. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75326. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75327. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75328. if (index > -1) {
  75329. this._onPhysicsCollideCallbacks.splice(index, 1);
  75330. }
  75331. else {
  75332. BABYLON.Tools.Warn("Function to remove was not found");
  75333. }
  75334. };
  75335. PhysicsImpostor.prototype.getParentsRotation = function () {
  75336. var parent = this.object.parent;
  75337. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75338. while (parent) {
  75339. if (parent.rotationQuaternion) {
  75340. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75341. }
  75342. else {
  75343. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75344. }
  75345. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75346. parent = parent.parent;
  75347. }
  75348. return this._tmpQuat;
  75349. };
  75350. /**
  75351. * Apply a force
  75352. */
  75353. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75354. if (this._physicsEngine) {
  75355. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75356. }
  75357. return this;
  75358. };
  75359. /**
  75360. * Apply an impulse
  75361. */
  75362. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75363. if (this._physicsEngine) {
  75364. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75365. }
  75366. return this;
  75367. };
  75368. /**
  75369. * A help function to create a joint.
  75370. */
  75371. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75372. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75373. this.addJoint(otherImpostor, joint);
  75374. return this;
  75375. };
  75376. /**
  75377. * Add a joint to this impostor with a different impostor.
  75378. */
  75379. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75380. this._joints.push({
  75381. otherImpostor: otherImpostor,
  75382. joint: joint
  75383. });
  75384. if (this._physicsEngine) {
  75385. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75386. }
  75387. return this;
  75388. };
  75389. /**
  75390. * Will keep this body still, in a sleep mode.
  75391. */
  75392. PhysicsImpostor.prototype.sleep = function () {
  75393. if (this._physicsEngine) {
  75394. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75395. }
  75396. return this;
  75397. };
  75398. /**
  75399. * Wake the body up.
  75400. */
  75401. PhysicsImpostor.prototype.wakeUp = function () {
  75402. if (this._physicsEngine) {
  75403. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75404. }
  75405. return this;
  75406. };
  75407. PhysicsImpostor.prototype.clone = function (newObject) {
  75408. if (!newObject)
  75409. return null;
  75410. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75411. };
  75412. PhysicsImpostor.prototype.dispose = function () {
  75413. var _this = this;
  75414. //no dispose if no physics engine is available.
  75415. if (!this._physicsEngine) {
  75416. return;
  75417. }
  75418. this._joints.forEach(function (j) {
  75419. if (_this._physicsEngine) {
  75420. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75421. }
  75422. });
  75423. //dispose the physics body
  75424. this._physicsEngine.removeImpostor(this);
  75425. if (this.parent) {
  75426. this.parent.forceUpdate();
  75427. }
  75428. else {
  75429. /*this._object.getChildMeshes().forEach(function(mesh) {
  75430. if (mesh.physicsImpostor) {
  75431. if (disposeChildren) {
  75432. mesh.physicsImpostor.dispose();
  75433. mesh.physicsImpostor = null;
  75434. }
  75435. }
  75436. })*/
  75437. }
  75438. this._isDisposed = true;
  75439. };
  75440. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75441. this._deltaPosition.copyFrom(position);
  75442. };
  75443. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75444. if (!this._deltaRotation) {
  75445. this._deltaRotation = new BABYLON.Quaternion();
  75446. }
  75447. this._deltaRotation.copyFrom(rotation);
  75448. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75449. };
  75450. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75451. if (this._physicsEngine) {
  75452. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75453. }
  75454. return this;
  75455. };
  75456. PhysicsImpostor.prototype.getRadius = function () {
  75457. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75458. };
  75459. /**
  75460. * Sync a bone with this impostor
  75461. * @param bone The bone to sync to the impostor.
  75462. * @param boneMesh The mesh that the bone is influencing.
  75463. * @param jointPivot The pivot of the joint / bone in local space.
  75464. * @param distToJoint Optional distance from the impostor to the joint.
  75465. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75466. */
  75467. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75468. var tempVec = PhysicsImpostor._tmpVecs[0];
  75469. var mesh = this.object;
  75470. if (mesh.rotationQuaternion) {
  75471. if (adjustRotation) {
  75472. var tempQuat = PhysicsImpostor._tmpQuat;
  75473. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75474. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75475. }
  75476. else {
  75477. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75478. }
  75479. }
  75480. tempVec.x = 0;
  75481. tempVec.y = 0;
  75482. tempVec.z = 0;
  75483. if (jointPivot) {
  75484. tempVec.x = jointPivot.x;
  75485. tempVec.y = jointPivot.y;
  75486. tempVec.z = jointPivot.z;
  75487. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75488. if (distToJoint === undefined || distToJoint === null) {
  75489. distToJoint = jointPivot.length();
  75490. }
  75491. tempVec.x *= distToJoint;
  75492. tempVec.y *= distToJoint;
  75493. tempVec.z *= distToJoint;
  75494. }
  75495. if (bone.getParent()) {
  75496. tempVec.addInPlace(mesh.getAbsolutePosition());
  75497. bone.setAbsolutePosition(tempVec, boneMesh);
  75498. }
  75499. else {
  75500. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75501. boneMesh.position.x -= tempVec.x;
  75502. boneMesh.position.y -= tempVec.y;
  75503. boneMesh.position.z -= tempVec.z;
  75504. }
  75505. };
  75506. /**
  75507. * Sync impostor to a bone
  75508. * @param bone The bone that the impostor will be synced to.
  75509. * @param boneMesh The mesh that the bone is influencing.
  75510. * @param jointPivot The pivot of the joint / bone in local space.
  75511. * @param distToJoint Optional distance from the impostor to the joint.
  75512. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75513. * @param boneAxis Optional vector3 axis the bone is aligned with
  75514. */
  75515. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75516. var mesh = this.object;
  75517. if (mesh.rotationQuaternion) {
  75518. if (adjustRotation) {
  75519. var tempQuat = PhysicsImpostor._tmpQuat;
  75520. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75521. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75522. }
  75523. else {
  75524. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75525. }
  75526. }
  75527. var pos = PhysicsImpostor._tmpVecs[0];
  75528. var boneDir = PhysicsImpostor._tmpVecs[1];
  75529. if (!boneAxis) {
  75530. boneAxis = PhysicsImpostor._tmpVecs[2];
  75531. boneAxis.x = 0;
  75532. boneAxis.y = 1;
  75533. boneAxis.z = 0;
  75534. }
  75535. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75536. bone.getAbsolutePositionToRef(boneMesh, pos);
  75537. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75538. distToJoint = jointPivot.length();
  75539. }
  75540. if (distToJoint !== undefined && distToJoint !== null) {
  75541. pos.x += boneDir.x * distToJoint;
  75542. pos.y += boneDir.y * distToJoint;
  75543. pos.z += boneDir.z * distToJoint;
  75544. }
  75545. mesh.setAbsolutePosition(pos);
  75546. };
  75547. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75548. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75549. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75550. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75551. //Impostor types
  75552. PhysicsImpostor.NoImpostor = 0;
  75553. PhysicsImpostor.SphereImpostor = 1;
  75554. PhysicsImpostor.BoxImpostor = 2;
  75555. PhysicsImpostor.PlaneImpostor = 3;
  75556. PhysicsImpostor.MeshImpostor = 4;
  75557. PhysicsImpostor.CylinderImpostor = 7;
  75558. PhysicsImpostor.ParticleImpostor = 8;
  75559. PhysicsImpostor.HeightmapImpostor = 9;
  75560. return PhysicsImpostor;
  75561. }());
  75562. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75563. })(BABYLON || (BABYLON = {}));
  75564. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75565. var BABYLON;
  75566. (function (BABYLON) {
  75567. var PhysicsEngine = /** @class */ (function () {
  75568. function PhysicsEngine(gravity, _physicsPlugin) {
  75569. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75570. this._physicsPlugin = _physicsPlugin;
  75571. //new methods and parameters
  75572. this._impostors = [];
  75573. this._joints = [];
  75574. if (!this._physicsPlugin.isSupported()) {
  75575. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75576. + "Please make sure it is included.");
  75577. }
  75578. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75579. this.setGravity(gravity);
  75580. this.setTimeStep();
  75581. }
  75582. PhysicsEngine.prototype.setGravity = function (gravity) {
  75583. this.gravity = gravity;
  75584. this._physicsPlugin.setGravity(this.gravity);
  75585. };
  75586. /**
  75587. * Set the time step of the physics engine.
  75588. * default is 1/60.
  75589. * To slow it down, enter 1/600 for example.
  75590. * To speed it up, 1/30
  75591. * @param {number} newTimeStep the new timestep to apply to this world.
  75592. */
  75593. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75594. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75595. this._physicsPlugin.setTimeStep(newTimeStep);
  75596. };
  75597. /**
  75598. * Get the time step of the physics engine.
  75599. */
  75600. PhysicsEngine.prototype.getTimeStep = function () {
  75601. return this._physicsPlugin.getTimeStep();
  75602. };
  75603. PhysicsEngine.prototype.dispose = function () {
  75604. this._impostors.forEach(function (impostor) {
  75605. impostor.dispose();
  75606. });
  75607. this._physicsPlugin.dispose();
  75608. };
  75609. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75610. return this._physicsPlugin.name;
  75611. };
  75612. /**
  75613. * Adding a new impostor for the impostor tracking.
  75614. * This will be done by the impostor itself.
  75615. * @param {PhysicsImpostor} impostor the impostor to add
  75616. */
  75617. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75618. impostor.uniqueId = this._impostors.push(impostor);
  75619. //if no parent, generate the body
  75620. if (!impostor.parent) {
  75621. this._physicsPlugin.generatePhysicsBody(impostor);
  75622. }
  75623. };
  75624. /**
  75625. * Remove an impostor from the engine.
  75626. * This impostor and its mesh will not longer be updated by the physics engine.
  75627. * @param {PhysicsImpostor} impostor the impostor to remove
  75628. */
  75629. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75630. var index = this._impostors.indexOf(impostor);
  75631. if (index > -1) {
  75632. var removed = this._impostors.splice(index, 1);
  75633. //Is it needed?
  75634. if (removed.length) {
  75635. //this will also remove it from the world.
  75636. removed[0].physicsBody = null;
  75637. }
  75638. }
  75639. };
  75640. /**
  75641. * Add a joint to the physics engine
  75642. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75643. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75644. * @param {PhysicsJoint} the joint that will connect both impostors.
  75645. */
  75646. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75647. var impostorJoint = {
  75648. mainImpostor: mainImpostor,
  75649. connectedImpostor: connectedImpostor,
  75650. joint: joint
  75651. };
  75652. joint.physicsPlugin = this._physicsPlugin;
  75653. this._joints.push(impostorJoint);
  75654. this._physicsPlugin.generateJoint(impostorJoint);
  75655. };
  75656. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75657. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75658. return (impostorJoint.connectedImpostor === connectedImpostor
  75659. && impostorJoint.joint === joint
  75660. && impostorJoint.mainImpostor === mainImpostor);
  75661. });
  75662. if (matchingJoints.length) {
  75663. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75664. //TODO remove it from the list as well
  75665. }
  75666. };
  75667. /**
  75668. * Called by the scene. no need to call it.
  75669. */
  75670. PhysicsEngine.prototype._step = function (delta) {
  75671. var _this = this;
  75672. //check if any mesh has no body / requires an update
  75673. this._impostors.forEach(function (impostor) {
  75674. if (impostor.isBodyInitRequired()) {
  75675. _this._physicsPlugin.generatePhysicsBody(impostor);
  75676. }
  75677. });
  75678. if (delta > 0.1) {
  75679. delta = 0.1;
  75680. }
  75681. else if (delta <= 0) {
  75682. delta = 1.0 / 60.0;
  75683. }
  75684. this._physicsPlugin.executeStep(delta, this._impostors);
  75685. };
  75686. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75687. return this._physicsPlugin;
  75688. };
  75689. PhysicsEngine.prototype.getImpostors = function () {
  75690. return this._impostors;
  75691. };
  75692. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75693. for (var i = 0; i < this._impostors.length; ++i) {
  75694. if (this._impostors[i].object === object) {
  75695. return this._impostors[i];
  75696. }
  75697. }
  75698. return null;
  75699. };
  75700. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75701. for (var i = 0; i < this._impostors.length; ++i) {
  75702. if (this._impostors[i].physicsBody === body) {
  75703. return this._impostors[i];
  75704. }
  75705. }
  75706. return null;
  75707. };
  75708. // Statics
  75709. PhysicsEngine.Epsilon = 0.001;
  75710. return PhysicsEngine;
  75711. }());
  75712. BABYLON.PhysicsEngine = PhysicsEngine;
  75713. })(BABYLON || (BABYLON = {}));
  75714. //# sourceMappingURL=babylon.physicsEngine.js.map
  75715. var BABYLON;
  75716. (function (BABYLON) {
  75717. var PhysicsHelper = /** @class */ (function () {
  75718. function PhysicsHelper(scene) {
  75719. this._scene = scene;
  75720. this._physicsEngine = this._scene.getPhysicsEngine();
  75721. if (!this._physicsEngine) {
  75722. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75723. }
  75724. }
  75725. /**
  75726. * @param {Vector3} origin the origin of the explosion
  75727. * @param {number} radius the explosion radius
  75728. * @param {number} strength the explosion strength
  75729. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75730. */
  75731. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75732. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75733. if (!this._physicsEngine) {
  75734. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75735. return null;
  75736. }
  75737. var impostors = this._physicsEngine.getImpostors();
  75738. if (impostors.length === 0) {
  75739. return null;
  75740. }
  75741. var event = new PhysicsRadialExplosionEvent(this._scene);
  75742. impostors.forEach(function (impostor) {
  75743. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75744. if (!impostorForceAndContactPoint) {
  75745. return;
  75746. }
  75747. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75748. });
  75749. event.dispose(false);
  75750. return event;
  75751. };
  75752. /**
  75753. * @param {Vector3} origin the origin of the explosion
  75754. * @param {number} radius the explosion radius
  75755. * @param {number} strength the explosion strength
  75756. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75757. */
  75758. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75759. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75760. if (!this._physicsEngine) {
  75761. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75762. return null;
  75763. }
  75764. var impostors = this._physicsEngine.getImpostors();
  75765. if (impostors.length === 0) {
  75766. return null;
  75767. }
  75768. var event = new PhysicsRadialExplosionEvent(this._scene);
  75769. impostors.forEach(function (impostor) {
  75770. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75771. if (!impostorForceAndContactPoint) {
  75772. return;
  75773. }
  75774. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75775. });
  75776. event.dispose(false);
  75777. return event;
  75778. };
  75779. /**
  75780. * @param {Vector3} origin the origin of the explosion
  75781. * @param {number} radius the explosion radius
  75782. * @param {number} strength the explosion strength
  75783. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75784. */
  75785. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75786. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75787. if (!this._physicsEngine) {
  75788. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75789. return null;
  75790. }
  75791. var impostors = this._physicsEngine.getImpostors();
  75792. if (impostors.length === 0) {
  75793. return null;
  75794. }
  75795. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75796. event.dispose(false);
  75797. return event;
  75798. };
  75799. /**
  75800. * @param {Vector3} origin the origin of the updraft
  75801. * @param {number} radius the radius of the updraft
  75802. * @param {number} strength the strength of the updraft
  75803. * @param {number} height the height of the updraft
  75804. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75805. */
  75806. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75807. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75808. if (!this._physicsEngine) {
  75809. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75810. return null;
  75811. }
  75812. if (this._physicsEngine.getImpostors().length === 0) {
  75813. return null;
  75814. }
  75815. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75816. event.dispose(false);
  75817. return event;
  75818. };
  75819. /**
  75820. * @param {Vector3} origin the of the vortex
  75821. * @param {number} radius the radius of the vortex
  75822. * @param {number} strength the strength of the vortex
  75823. * @param {number} height the height of the vortex
  75824. */
  75825. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75826. if (!this._physicsEngine) {
  75827. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75828. return null;
  75829. }
  75830. if (this._physicsEngine.getImpostors().length === 0) {
  75831. return null;
  75832. }
  75833. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75834. event.dispose(false);
  75835. return event;
  75836. };
  75837. return PhysicsHelper;
  75838. }());
  75839. BABYLON.PhysicsHelper = PhysicsHelper;
  75840. /***** Radial explosion *****/
  75841. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75842. function PhysicsRadialExplosionEvent(scene) {
  75843. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75844. this._rays = [];
  75845. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75846. this._scene = scene;
  75847. }
  75848. /**
  75849. * Returns the data related to the radial explosion event (sphere & rays).
  75850. * @returns {PhysicsRadialExplosionEventData}
  75851. */
  75852. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75853. this._dataFetched = true;
  75854. return {
  75855. sphere: this._sphere,
  75856. rays: this._rays,
  75857. };
  75858. };
  75859. /**
  75860. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75861. * @param impostor
  75862. * @param {Vector3} origin the origin of the explosion
  75863. * @param {number} radius the explosion radius
  75864. * @param {number} strength the explosion strength
  75865. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75866. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75867. */
  75868. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75869. if (impostor.mass === 0) {
  75870. return null;
  75871. }
  75872. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75873. return null;
  75874. }
  75875. if (impostor.object.getClassName() !== 'Mesh') {
  75876. return null;
  75877. }
  75878. var impostorObject = impostor.object;
  75879. var impostorObjectCenter = impostor.getObjectCenter();
  75880. var direction = impostorObjectCenter.subtract(origin);
  75881. var ray = new BABYLON.Ray(origin, direction, radius);
  75882. this._rays.push(ray);
  75883. var hit = ray.intersectsMesh(impostorObject);
  75884. var contactPoint = hit.pickedPoint;
  75885. if (!contactPoint) {
  75886. return null;
  75887. }
  75888. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75889. if (distanceFromOrigin > radius) {
  75890. return null;
  75891. }
  75892. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75893. ? strength
  75894. : strength * (1 - (distanceFromOrigin / radius));
  75895. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75896. return { force: force, contactPoint: contactPoint };
  75897. };
  75898. /**
  75899. * Disposes the sphere.
  75900. * @param {bolean} force
  75901. */
  75902. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75903. var _this = this;
  75904. if (force === void 0) { force = true; }
  75905. if (force) {
  75906. this._sphere.dispose();
  75907. }
  75908. else {
  75909. setTimeout(function () {
  75910. if (!_this._dataFetched) {
  75911. _this._sphere.dispose();
  75912. }
  75913. }, 0);
  75914. }
  75915. };
  75916. /*** Helpers ***/
  75917. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75918. if (!this._sphere) {
  75919. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75920. this._sphere.isVisible = false;
  75921. }
  75922. };
  75923. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75924. var impostorObject = impostor.object;
  75925. this._prepareSphere();
  75926. this._sphere.position = origin;
  75927. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75928. this._sphere._updateBoundingInfo();
  75929. this._sphere.computeWorldMatrix(true);
  75930. return this._sphere.intersectsMesh(impostorObject, true);
  75931. };
  75932. return PhysicsRadialExplosionEvent;
  75933. }());
  75934. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75935. /***** Gravitational Field *****/
  75936. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75937. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75938. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75939. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75940. this._physicsHelper = physicsHelper;
  75941. this._scene = scene;
  75942. this._origin = origin;
  75943. this._radius = radius;
  75944. this._strength = strength;
  75945. this._falloff = falloff;
  75946. this._tickCallback = this._tick.bind(this);
  75947. }
  75948. /**
  75949. * Returns the data related to the gravitational field event (sphere).
  75950. * @returns {PhysicsGravitationalFieldEventData}
  75951. */
  75952. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75953. this._dataFetched = true;
  75954. return {
  75955. sphere: this._sphere,
  75956. };
  75957. };
  75958. /**
  75959. * Enables the gravitational field.
  75960. */
  75961. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75962. this._tickCallback.call(this);
  75963. this._scene.registerBeforeRender(this._tickCallback);
  75964. };
  75965. /**
  75966. * Disables the gravitational field.
  75967. */
  75968. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75969. this._scene.unregisterBeforeRender(this._tickCallback);
  75970. };
  75971. /**
  75972. * Disposes the sphere.
  75973. * @param {bolean} force
  75974. */
  75975. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75976. var _this = this;
  75977. if (force === void 0) { force = true; }
  75978. if (force) {
  75979. this._sphere.dispose();
  75980. }
  75981. else {
  75982. setTimeout(function () {
  75983. if (!_this._dataFetched) {
  75984. _this._sphere.dispose();
  75985. }
  75986. }, 0);
  75987. }
  75988. };
  75989. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75990. // Since the params won't change, we fetch the event only once
  75991. if (this._sphere) {
  75992. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75993. }
  75994. else {
  75995. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75996. if (radialExplosionEvent) {
  75997. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75998. }
  75999. }
  76000. };
  76001. return PhysicsGravitationalFieldEvent;
  76002. }());
  76003. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76004. /***** Updraft *****/
  76005. var PhysicsUpdraftEvent = /** @class */ (function () {
  76006. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76007. this._scene = _scene;
  76008. this._origin = _origin;
  76009. this._radius = _radius;
  76010. this._strength = _strength;
  76011. this._height = _height;
  76012. this._updraftMode = _updraftMode;
  76013. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76014. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76015. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76016. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76017. this._physicsEngine = this._scene.getPhysicsEngine();
  76018. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76019. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76020. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76021. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76022. }
  76023. this._tickCallback = this._tick.bind(this);
  76024. }
  76025. /**
  76026. * Returns the data related to the updraft event (cylinder).
  76027. * @returns {PhysicsUpdraftEventData}
  76028. */
  76029. PhysicsUpdraftEvent.prototype.getData = function () {
  76030. this._dataFetched = true;
  76031. return {
  76032. cylinder: this._cylinder,
  76033. };
  76034. };
  76035. /**
  76036. * Enables the updraft.
  76037. */
  76038. PhysicsUpdraftEvent.prototype.enable = function () {
  76039. this._tickCallback.call(this);
  76040. this._scene.registerBeforeRender(this._tickCallback);
  76041. };
  76042. /**
  76043. * Disables the cortex.
  76044. */
  76045. PhysicsUpdraftEvent.prototype.disable = function () {
  76046. this._scene.unregisterBeforeRender(this._tickCallback);
  76047. };
  76048. /**
  76049. * Disposes the sphere.
  76050. * @param {bolean} force
  76051. */
  76052. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76053. var _this = this;
  76054. if (force === void 0) { force = true; }
  76055. if (force) {
  76056. this._cylinder.dispose();
  76057. }
  76058. else {
  76059. setTimeout(function () {
  76060. if (!_this._dataFetched) {
  76061. _this._cylinder.dispose();
  76062. }
  76063. }, 0);
  76064. }
  76065. };
  76066. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76067. if (impostor.mass === 0) {
  76068. return null;
  76069. }
  76070. if (!this._intersectsWithCylinder(impostor)) {
  76071. return null;
  76072. }
  76073. var impostorObjectCenter = impostor.getObjectCenter();
  76074. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76075. var direction = this._originDirection;
  76076. }
  76077. else {
  76078. var direction = impostorObjectCenter.subtract(this._originTop);
  76079. }
  76080. var multiplier = this._strength * -1;
  76081. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76082. return { force: force, contactPoint: impostorObjectCenter };
  76083. };
  76084. PhysicsUpdraftEvent.prototype._tick = function () {
  76085. var _this = this;
  76086. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76087. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76088. if (!impostorForceAndContactPoint) {
  76089. return;
  76090. }
  76091. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76092. });
  76093. };
  76094. /*** Helpers ***/
  76095. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76096. if (!this._cylinder) {
  76097. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76098. height: this._height,
  76099. diameter: this._radius * 2,
  76100. }, this._scene);
  76101. this._cylinder.isVisible = false;
  76102. }
  76103. };
  76104. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76105. var impostorObject = impostor.object;
  76106. this._prepareCylinder();
  76107. this._cylinder.position = this._cylinderPosition;
  76108. return this._cylinder.intersectsMesh(impostorObject, true);
  76109. };
  76110. return PhysicsUpdraftEvent;
  76111. }());
  76112. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76113. /***** Vortex *****/
  76114. var PhysicsVortexEvent = /** @class */ (function () {
  76115. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76116. this._scene = _scene;
  76117. this._origin = _origin;
  76118. this._radius = _radius;
  76119. this._strength = _strength;
  76120. this._height = _height;
  76121. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76122. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76123. this._updraftMultiplier = 0.02;
  76124. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76125. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76126. this._physicsEngine = this._scene.getPhysicsEngine();
  76127. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76128. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76129. this._tickCallback = this._tick.bind(this);
  76130. }
  76131. /**
  76132. * Returns the data related to the vortex event (cylinder).
  76133. * @returns {PhysicsVortexEventData}
  76134. */
  76135. PhysicsVortexEvent.prototype.getData = function () {
  76136. this._dataFetched = true;
  76137. return {
  76138. cylinder: this._cylinder,
  76139. };
  76140. };
  76141. /**
  76142. * Enables the vortex.
  76143. */
  76144. PhysicsVortexEvent.prototype.enable = function () {
  76145. this._tickCallback.call(this);
  76146. this._scene.registerBeforeRender(this._tickCallback);
  76147. };
  76148. /**
  76149. * Disables the cortex.
  76150. */
  76151. PhysicsVortexEvent.prototype.disable = function () {
  76152. this._scene.unregisterBeforeRender(this._tickCallback);
  76153. };
  76154. /**
  76155. * Disposes the sphere.
  76156. * @param {bolean} force
  76157. */
  76158. PhysicsVortexEvent.prototype.dispose = function (force) {
  76159. var _this = this;
  76160. if (force === void 0) { force = true; }
  76161. if (force) {
  76162. this._cylinder.dispose();
  76163. }
  76164. else {
  76165. setTimeout(function () {
  76166. if (!_this._dataFetched) {
  76167. _this._cylinder.dispose();
  76168. }
  76169. }, 0);
  76170. }
  76171. };
  76172. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76173. if (impostor.mass === 0) {
  76174. return null;
  76175. }
  76176. if (!this._intersectsWithCylinder(impostor)) {
  76177. return null;
  76178. }
  76179. if (impostor.object.getClassName() !== 'Mesh') {
  76180. return null;
  76181. }
  76182. var impostorObject = impostor.object;
  76183. var impostorObjectCenter = impostor.getObjectCenter();
  76184. 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)
  76185. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76186. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76187. var hit = ray.intersectsMesh(impostorObject);
  76188. var contactPoint = hit.pickedPoint;
  76189. if (!contactPoint) {
  76190. return null;
  76191. }
  76192. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76193. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76194. var directionToOrigin = contactPoint.normalize();
  76195. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76196. directionToOrigin = directionToOrigin.negate();
  76197. }
  76198. // TODO: find a more physically based solution
  76199. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76200. var forceX = directionToOrigin.x * this._strength / 8;
  76201. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76202. var forceZ = directionToOrigin.z * this._strength / 8;
  76203. }
  76204. else {
  76205. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76206. var forceY = this._originTop.y * this._updraftMultiplier;
  76207. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76208. }
  76209. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76210. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76211. return { force: force, contactPoint: impostorObjectCenter };
  76212. };
  76213. PhysicsVortexEvent.prototype._tick = function () {
  76214. var _this = this;
  76215. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76216. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76217. if (!impostorForceAndContactPoint) {
  76218. return;
  76219. }
  76220. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76221. });
  76222. };
  76223. /*** Helpers ***/
  76224. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76225. if (!this._cylinder) {
  76226. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76227. height: this._height,
  76228. diameter: this._radius * 2,
  76229. }, this._scene);
  76230. this._cylinder.isVisible = false;
  76231. }
  76232. };
  76233. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76234. var impostorObject = impostor.object;
  76235. this._prepareCylinder();
  76236. this._cylinder.position = this._cylinderPosition;
  76237. return this._cylinder.intersectsMesh(impostorObject, true);
  76238. };
  76239. return PhysicsVortexEvent;
  76240. }());
  76241. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76242. /***** Enums *****/
  76243. /**
  76244. * The strenght of the force in correspondence to the distance of the affected object
  76245. */
  76246. var PhysicsRadialImpulseFalloff;
  76247. (function (PhysicsRadialImpulseFalloff) {
  76248. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76249. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76250. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76251. /**
  76252. * The strenght of the force in correspondence to the distance of the affected object
  76253. */
  76254. var PhysicsUpdraftMode;
  76255. (function (PhysicsUpdraftMode) {
  76256. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76257. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76258. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76259. })(BABYLON || (BABYLON = {}));
  76260. //# sourceMappingURL=babylon.physicsHelper.js.map
  76261. var BABYLON;
  76262. (function (BABYLON) {
  76263. var CannonJSPlugin = /** @class */ (function () {
  76264. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76265. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76266. if (iterations === void 0) { iterations = 10; }
  76267. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76268. this.name = "CannonJSPlugin";
  76269. this._physicsMaterials = new Array();
  76270. this._fixedTimeStep = 1 / 60;
  76271. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76272. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76273. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76274. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76275. this._tmpPosition = BABYLON.Vector3.Zero();
  76276. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76277. this._tmpUnityRotation = new BABYLON.Quaternion();
  76278. if (!this.isSupported()) {
  76279. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76280. return;
  76281. }
  76282. this._extendNamespace();
  76283. this.world = new this.BJSCANNON.World();
  76284. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76285. this.world.solver.iterations = iterations;
  76286. }
  76287. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76288. this.world.gravity.copy(gravity);
  76289. };
  76290. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76291. this._fixedTimeStep = timeStep;
  76292. };
  76293. CannonJSPlugin.prototype.getTimeStep = function () {
  76294. return this._fixedTimeStep;
  76295. };
  76296. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76297. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76298. };
  76299. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76300. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76301. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76302. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76303. };
  76304. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76305. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76306. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76307. impostor.physicsBody.applyForce(impulse, worldPoint);
  76308. };
  76309. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76310. //parent-child relationship. Does this impostor has a parent impostor?
  76311. if (impostor.parent) {
  76312. if (impostor.physicsBody) {
  76313. this.removePhysicsBody(impostor);
  76314. //TODO is that needed?
  76315. impostor.forceUpdate();
  76316. }
  76317. return;
  76318. }
  76319. //should a new body be created for this impostor?
  76320. if (impostor.isBodyInitRequired()) {
  76321. var shape = this._createShape(impostor);
  76322. //unregister events, if body is being changed
  76323. var oldBody = impostor.physicsBody;
  76324. if (oldBody) {
  76325. this.removePhysicsBody(impostor);
  76326. }
  76327. //create the body and material
  76328. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76329. var bodyCreationObject = {
  76330. mass: impostor.getParam("mass"),
  76331. material: material
  76332. };
  76333. // A simple extend, in case native options were used.
  76334. var nativeOptions = impostor.getParam("nativeOptions");
  76335. for (var key in nativeOptions) {
  76336. if (nativeOptions.hasOwnProperty(key)) {
  76337. bodyCreationObject[key] = nativeOptions[key];
  76338. }
  76339. }
  76340. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76341. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76342. this.world.addEventListener("preStep", impostor.beforeStep);
  76343. this.world.addEventListener("postStep", impostor.afterStep);
  76344. impostor.physicsBody.addShape(shape);
  76345. this.world.add(impostor.physicsBody);
  76346. //try to keep the body moving in the right direction by taking old properties.
  76347. //Should be tested!
  76348. if (oldBody) {
  76349. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76350. impostor.physicsBody[param].copy(oldBody[param]);
  76351. });
  76352. }
  76353. this._processChildMeshes(impostor);
  76354. }
  76355. //now update the body's transformation
  76356. this._updatePhysicsBodyTransformation(impostor);
  76357. };
  76358. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76359. var _this = this;
  76360. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76361. var currentRotation = mainImpostor.object.rotationQuaternion;
  76362. if (meshChildren.length) {
  76363. var processMesh = function (localPosition, mesh) {
  76364. if (!currentRotation || !mesh.rotationQuaternion) {
  76365. return;
  76366. }
  76367. var childImpostor = mesh.getPhysicsImpostor();
  76368. if (childImpostor) {
  76369. var parent = childImpostor.parent;
  76370. if (parent !== mainImpostor) {
  76371. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76372. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76373. if (childImpostor.physicsBody) {
  76374. _this.removePhysicsBody(childImpostor);
  76375. childImpostor.physicsBody = null;
  76376. }
  76377. childImpostor.parent = mainImpostor;
  76378. childImpostor.resetUpdateFlags();
  76379. 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));
  76380. //Add the mass of the children.
  76381. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76382. }
  76383. }
  76384. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76385. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76386. };
  76387. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76388. }
  76389. };
  76390. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76391. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76392. this.world.removeEventListener("preStep", impostor.beforeStep);
  76393. this.world.removeEventListener("postStep", impostor.afterStep);
  76394. this.world.remove(impostor.physicsBody);
  76395. };
  76396. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76397. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76398. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76399. if (!mainBody || !connectedBody) {
  76400. return;
  76401. }
  76402. var constraint;
  76403. var jointData = impostorJoint.joint.jointData;
  76404. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76405. var constraintData = {
  76406. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76407. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76408. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76409. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76410. maxForce: jointData.nativeParams.maxForce,
  76411. collideConnected: !!jointData.collision
  76412. };
  76413. switch (impostorJoint.joint.type) {
  76414. case BABYLON.PhysicsJoint.HingeJoint:
  76415. case BABYLON.PhysicsJoint.Hinge2Joint:
  76416. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76417. break;
  76418. case BABYLON.PhysicsJoint.DistanceJoint:
  76419. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76420. break;
  76421. case BABYLON.PhysicsJoint.SpringJoint:
  76422. var springData = jointData;
  76423. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76424. restLength: springData.length,
  76425. stiffness: springData.stiffness,
  76426. damping: springData.damping,
  76427. localAnchorA: constraintData.pivotA,
  76428. localAnchorB: constraintData.pivotB
  76429. });
  76430. break;
  76431. case BABYLON.PhysicsJoint.LockJoint:
  76432. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76433. break;
  76434. case BABYLON.PhysicsJoint.PointToPointJoint:
  76435. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76436. default:
  76437. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76438. break;
  76439. }
  76440. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76441. constraint.collideConnected = !!jointData.collision;
  76442. impostorJoint.joint.physicsJoint = constraint;
  76443. //don't add spring as constraint, as it is not one.
  76444. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76445. this.world.addConstraint(constraint);
  76446. }
  76447. else {
  76448. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76449. constraint.applyForce();
  76450. });
  76451. }
  76452. };
  76453. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76454. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76455. };
  76456. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76457. var index;
  76458. var mat;
  76459. for (index = 0; index < this._physicsMaterials.length; index++) {
  76460. mat = this._physicsMaterials[index];
  76461. if (mat.friction === friction && mat.restitution === restitution) {
  76462. return mat;
  76463. }
  76464. }
  76465. var currentMat = new this.BJSCANNON.Material(name);
  76466. currentMat.friction = friction;
  76467. currentMat.restitution = restitution;
  76468. this._physicsMaterials.push(currentMat);
  76469. return currentMat;
  76470. };
  76471. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76472. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76473. };
  76474. CannonJSPlugin.prototype._createShape = function (impostor) {
  76475. var object = impostor.object;
  76476. var returnValue;
  76477. var extendSize = impostor.getObjectExtendSize();
  76478. switch (impostor.type) {
  76479. case BABYLON.PhysicsImpostor.SphereImpostor:
  76480. var radiusX = extendSize.x;
  76481. var radiusY = extendSize.y;
  76482. var radiusZ = extendSize.z;
  76483. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76484. break;
  76485. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76486. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76487. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76488. break;
  76489. case BABYLON.PhysicsImpostor.BoxImpostor:
  76490. var box = extendSize.scale(0.5);
  76491. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76492. break;
  76493. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76494. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76495. returnValue = new this.BJSCANNON.Plane();
  76496. break;
  76497. case BABYLON.PhysicsImpostor.MeshImpostor:
  76498. // should transform the vertex data to world coordinates!!
  76499. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76500. var rawFaces = object.getIndices ? object.getIndices() : [];
  76501. if (!rawVerts)
  76502. return;
  76503. // get only scale! so the object could transform correctly.
  76504. var oldPosition = object.position.clone();
  76505. var oldRotation = object.rotation && object.rotation.clone();
  76506. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76507. object.position.copyFromFloats(0, 0, 0);
  76508. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76509. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76510. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76511. var transform = object.computeWorldMatrix(true);
  76512. // convert rawVerts to object space
  76513. var temp = new Array();
  76514. var index;
  76515. for (index = 0; index < rawVerts.length; index += 3) {
  76516. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76517. }
  76518. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76519. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76520. //now set back the transformation!
  76521. object.position.copyFrom(oldPosition);
  76522. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76523. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76524. break;
  76525. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76526. var oldPosition2 = object.position.clone();
  76527. var oldRotation2 = object.rotation && object.rotation.clone();
  76528. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76529. object.position.copyFromFloats(0, 0, 0);
  76530. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76531. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76532. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76533. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76534. returnValue = this._createHeightmap(object);
  76535. object.position.copyFrom(oldPosition2);
  76536. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76537. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76538. object.computeWorldMatrix(true);
  76539. break;
  76540. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76541. returnValue = new this.BJSCANNON.Particle();
  76542. break;
  76543. }
  76544. return returnValue;
  76545. };
  76546. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76547. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76548. var transform = object.computeWorldMatrix(true);
  76549. // convert rawVerts to object space
  76550. var temp = new Array();
  76551. var index;
  76552. for (index = 0; index < pos.length; index += 3) {
  76553. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76554. }
  76555. pos = temp;
  76556. var matrix = new Array();
  76557. //For now pointDepth will not be used and will be automatically calculated.
  76558. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76559. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76560. var boundingInfo = object.getBoundingInfo();
  76561. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76562. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76563. var elementSize = dim * 2 / arraySize;
  76564. for (var i = 0; i < pos.length; i = i + 3) {
  76565. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76566. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76567. var y = -pos[i + 2] + minY;
  76568. if (!matrix[x]) {
  76569. matrix[x] = [];
  76570. }
  76571. if (!matrix[x][z]) {
  76572. matrix[x][z] = y;
  76573. }
  76574. matrix[x][z] = Math.max(y, matrix[x][z]);
  76575. }
  76576. for (var x = 0; x <= arraySize; ++x) {
  76577. if (!matrix[x]) {
  76578. var loc = 1;
  76579. while (!matrix[(x + loc) % arraySize]) {
  76580. loc++;
  76581. }
  76582. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76583. //console.log("missing x", x);
  76584. }
  76585. for (var z = 0; z <= arraySize; ++z) {
  76586. if (!matrix[x][z]) {
  76587. var loc = 1;
  76588. var newValue;
  76589. while (newValue === undefined) {
  76590. newValue = matrix[x][(z + loc++) % arraySize];
  76591. }
  76592. matrix[x][z] = newValue;
  76593. }
  76594. }
  76595. }
  76596. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76597. elementSize: elementSize
  76598. });
  76599. //For future reference, needed for body transformation
  76600. shape.minY = minY;
  76601. return shape;
  76602. };
  76603. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76604. var object = impostor.object;
  76605. //make sure it is updated...
  76606. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76607. // The delta between the mesh position and the mesh bounding box center
  76608. var bInfo = object.getBoundingInfo();
  76609. if (!bInfo)
  76610. return;
  76611. var center = impostor.getObjectCenter();
  76612. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76613. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76614. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76615. this._tmpPosition.copyFrom(center);
  76616. var quaternion = object.rotationQuaternion;
  76617. if (!quaternion) {
  76618. return;
  76619. }
  76620. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76621. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76622. //-90 DEG in X, precalculated
  76623. quaternion = quaternion.multiply(this._minus90X);
  76624. //Invert! (Precalculated, 90 deg in X)
  76625. //No need to clone. this will never change.
  76626. impostor.setDeltaRotation(this._plus90X);
  76627. }
  76628. //If it is a heightfield, if should be centered.
  76629. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76630. var mesh = object;
  76631. var boundingInfo = mesh.getBoundingInfo();
  76632. //calculate the correct body position:
  76633. var rotationQuaternion = mesh.rotationQuaternion;
  76634. mesh.rotationQuaternion = this._tmpUnityRotation;
  76635. mesh.computeWorldMatrix(true);
  76636. //get original center with no rotation
  76637. var c = center.clone();
  76638. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76639. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76640. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76641. mesh.setPreTransformMatrix(p);
  76642. mesh.computeWorldMatrix(true);
  76643. //calculate the translation
  76644. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76645. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76646. //add it inverted to the delta
  76647. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76648. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76649. //rotation is back
  76650. mesh.rotationQuaternion = rotationQuaternion;
  76651. mesh.setPreTransformMatrix(oldPivot);
  76652. mesh.computeWorldMatrix(true);
  76653. }
  76654. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76655. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76656. //this._tmpPosition.copyFrom(object.position);
  76657. }
  76658. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76659. //Now update the impostor object
  76660. impostor.physicsBody.position.copy(this._tmpPosition);
  76661. impostor.physicsBody.quaternion.copy(quaternion);
  76662. };
  76663. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76664. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76665. if (impostor.object.rotationQuaternion) {
  76666. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76667. }
  76668. };
  76669. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76670. impostor.physicsBody.position.copy(newPosition);
  76671. impostor.physicsBody.quaternion.copy(newRotation);
  76672. };
  76673. CannonJSPlugin.prototype.isSupported = function () {
  76674. return this.BJSCANNON !== undefined;
  76675. };
  76676. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76677. impostor.physicsBody.velocity.copy(velocity);
  76678. };
  76679. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76680. impostor.physicsBody.angularVelocity.copy(velocity);
  76681. };
  76682. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76683. var v = impostor.physicsBody.velocity;
  76684. if (!v) {
  76685. return null;
  76686. }
  76687. return new BABYLON.Vector3(v.x, v.y, v.z);
  76688. };
  76689. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76690. var v = impostor.physicsBody.angularVelocity;
  76691. if (!v) {
  76692. return null;
  76693. }
  76694. return new BABYLON.Vector3(v.x, v.y, v.z);
  76695. };
  76696. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76697. impostor.physicsBody.mass = mass;
  76698. impostor.physicsBody.updateMassProperties();
  76699. };
  76700. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76701. return impostor.physicsBody.mass;
  76702. };
  76703. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76704. return impostor.physicsBody.material.friction;
  76705. };
  76706. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76707. impostor.physicsBody.material.friction = friction;
  76708. };
  76709. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76710. return impostor.physicsBody.material.restitution;
  76711. };
  76712. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76713. impostor.physicsBody.material.restitution = restitution;
  76714. };
  76715. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76716. impostor.physicsBody.sleep();
  76717. };
  76718. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76719. impostor.physicsBody.wakeUp();
  76720. };
  76721. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76722. joint.physicsJoint.distance = maxDistance;
  76723. };
  76724. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76725. // if (!motorIndex) {
  76726. // joint.physicsJoint.enableMotor();
  76727. // }
  76728. // }
  76729. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76730. // if (!motorIndex) {
  76731. // joint.physicsJoint.disableMotor();
  76732. // }
  76733. // }
  76734. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76735. if (!motorIndex) {
  76736. joint.physicsJoint.enableMotor();
  76737. joint.physicsJoint.setMotorSpeed(speed);
  76738. if (maxForce) {
  76739. this.setLimit(joint, maxForce);
  76740. }
  76741. }
  76742. };
  76743. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76744. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76745. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76746. };
  76747. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76748. var body = impostor.physicsBody;
  76749. mesh.position.x = body.position.x;
  76750. mesh.position.y = body.position.y;
  76751. mesh.position.z = body.position.z;
  76752. if (mesh.rotationQuaternion) {
  76753. mesh.rotationQuaternion.x = body.quaternion.x;
  76754. mesh.rotationQuaternion.y = body.quaternion.y;
  76755. mesh.rotationQuaternion.z = body.quaternion.z;
  76756. mesh.rotationQuaternion.w = body.quaternion.w;
  76757. }
  76758. };
  76759. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76760. var shape = impostor.physicsBody.shapes[0];
  76761. return shape.boundingSphereRadius;
  76762. };
  76763. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76764. var shape = impostor.physicsBody.shapes[0];
  76765. result.x = shape.halfExtents.x * 2;
  76766. result.y = shape.halfExtents.y * 2;
  76767. result.z = shape.halfExtents.z * 2;
  76768. };
  76769. CannonJSPlugin.prototype.dispose = function () {
  76770. };
  76771. CannonJSPlugin.prototype._extendNamespace = function () {
  76772. //this will force cannon to execute at least one step when using interpolation
  76773. var step_tmp1 = new this.BJSCANNON.Vec3();
  76774. var Engine = this.BJSCANNON;
  76775. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76776. maxSubSteps = maxSubSteps || 10;
  76777. timeSinceLastCalled = timeSinceLastCalled || 0;
  76778. if (timeSinceLastCalled === 0) {
  76779. this.internalStep(dt);
  76780. this.time += dt;
  76781. }
  76782. else {
  76783. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76784. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76785. var t0 = performance.now();
  76786. for (var i = 0; i !== internalSteps; i++) {
  76787. this.internalStep(dt);
  76788. if (performance.now() - t0 > dt * 1000) {
  76789. break;
  76790. }
  76791. }
  76792. this.time += timeSinceLastCalled;
  76793. var h = this.time % dt;
  76794. var h_div_dt = h / dt;
  76795. var interpvelo = step_tmp1;
  76796. var bodies = this.bodies;
  76797. for (var j = 0; j !== bodies.length; j++) {
  76798. var b = bodies[j];
  76799. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76800. b.position.vsub(b.previousPosition, interpvelo);
  76801. interpvelo.scale(h_div_dt, interpvelo);
  76802. b.position.vadd(interpvelo, b.interpolatedPosition);
  76803. }
  76804. else {
  76805. b.interpolatedPosition.copy(b.position);
  76806. b.interpolatedQuaternion.copy(b.quaternion);
  76807. }
  76808. }
  76809. }
  76810. };
  76811. };
  76812. return CannonJSPlugin;
  76813. }());
  76814. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76815. })(BABYLON || (BABYLON = {}));
  76816. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76817. var BABYLON;
  76818. (function (BABYLON) {
  76819. var OimoJSPlugin = /** @class */ (function () {
  76820. function OimoJSPlugin(iterations) {
  76821. this.name = "OimoJSPlugin";
  76822. this._tmpImpostorsArray = [];
  76823. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76824. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76825. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76826. this.world.worldscale(1);
  76827. this.world.clear();
  76828. //making sure no stats are calculated
  76829. this.world.isNoStat = true;
  76830. }
  76831. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76832. this.world.gravity.copy(gravity);
  76833. };
  76834. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76835. this.world.timeStep = timeStep;
  76836. };
  76837. OimoJSPlugin.prototype.getTimeStep = function () {
  76838. return this.world.timeStep;
  76839. };
  76840. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76841. var _this = this;
  76842. impostors.forEach(function (impostor) {
  76843. impostor.beforeStep();
  76844. });
  76845. this.world.step();
  76846. impostors.forEach(function (impostor) {
  76847. impostor.afterStep();
  76848. //update the ordered impostors array
  76849. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76850. });
  76851. //check for collisions
  76852. var contact = this.world.contacts;
  76853. while (contact !== null) {
  76854. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76855. contact = contact.next;
  76856. continue;
  76857. }
  76858. //is this body colliding with any other? get the impostor
  76859. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76860. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76861. if (!mainImpostor || !collidingImpostor) {
  76862. contact = contact.next;
  76863. continue;
  76864. }
  76865. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76866. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76867. contact = contact.next;
  76868. }
  76869. };
  76870. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76871. var mass = impostor.physicsBody.massInfo.mass;
  76872. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76873. };
  76874. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76875. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76876. this.applyImpulse(impostor, force, contactPoint);
  76877. };
  76878. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76879. var _this = this;
  76880. //parent-child relationship. Does this impostor has a parent impostor?
  76881. if (impostor.parent) {
  76882. if (impostor.physicsBody) {
  76883. this.removePhysicsBody(impostor);
  76884. //TODO is that needed?
  76885. impostor.forceUpdate();
  76886. }
  76887. return;
  76888. }
  76889. if (impostor.isBodyInitRequired()) {
  76890. var bodyConfig = {
  76891. name: impostor.uniqueId,
  76892. //Oimo must have mass, also for static objects.
  76893. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76894. size: [],
  76895. type: [],
  76896. pos: [],
  76897. rot: [],
  76898. move: impostor.getParam("mass") !== 0,
  76899. //Supporting older versions of Oimo
  76900. world: this.world
  76901. };
  76902. var impostors = [impostor];
  76903. var addToArray = function (parent) {
  76904. if (!parent.getChildMeshes)
  76905. return;
  76906. parent.getChildMeshes().forEach(function (m) {
  76907. if (m.physicsImpostor) {
  76908. impostors.push(m.physicsImpostor);
  76909. //m.physicsImpostor._init();
  76910. }
  76911. });
  76912. };
  76913. addToArray(impostor.object);
  76914. var checkWithEpsilon_1 = function (value) {
  76915. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76916. };
  76917. impostors.forEach(function (i) {
  76918. if (!impostor.object.rotationQuaternion) {
  76919. return;
  76920. }
  76921. //get the correct bounding box
  76922. var oldQuaternion = i.object.rotationQuaternion;
  76923. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76924. x: impostor.object.rotationQuaternion.x,
  76925. y: impostor.object.rotationQuaternion.y,
  76926. z: impostor.object.rotationQuaternion.z,
  76927. s: impostor.object.rotationQuaternion.w
  76928. });
  76929. var extendSize = i.getObjectExtendSize();
  76930. if (i === impostor) {
  76931. var center = impostor.getObjectCenter();
  76932. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76933. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76934. //Can also use Array.prototype.push.apply
  76935. bodyConfig.pos.push(center.x);
  76936. bodyConfig.pos.push(center.y);
  76937. bodyConfig.pos.push(center.z);
  76938. //tmp solution
  76939. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76940. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76941. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76942. }
  76943. else {
  76944. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76945. bodyConfig.pos.push(localPosition.x);
  76946. bodyConfig.pos.push(localPosition.y);
  76947. bodyConfig.pos.push(localPosition.z);
  76948. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76949. bodyConfig.rot.push(0);
  76950. bodyConfig.rot.push(0);
  76951. bodyConfig.rot.push(0);
  76952. }
  76953. // register mesh
  76954. switch (i.type) {
  76955. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76956. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76957. case BABYLON.PhysicsImpostor.SphereImpostor:
  76958. var radiusX = extendSize.x;
  76959. var radiusY = extendSize.y;
  76960. var radiusZ = extendSize.z;
  76961. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76962. bodyConfig.type.push('sphere');
  76963. //due to the way oimo works with compounds, add 3 times
  76964. bodyConfig.size.push(size);
  76965. bodyConfig.size.push(size);
  76966. bodyConfig.size.push(size);
  76967. break;
  76968. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76969. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76970. var sizeY = checkWithEpsilon_1(extendSize.y);
  76971. bodyConfig.type.push('cylinder');
  76972. bodyConfig.size.push(sizeX);
  76973. bodyConfig.size.push(sizeY);
  76974. //due to the way oimo works with compounds, add one more value.
  76975. bodyConfig.size.push(sizeY);
  76976. break;
  76977. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76978. case BABYLON.PhysicsImpostor.BoxImpostor:
  76979. default:
  76980. var sizeX = checkWithEpsilon_1(extendSize.x);
  76981. var sizeY = checkWithEpsilon_1(extendSize.y);
  76982. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76983. bodyConfig.type.push('box');
  76984. bodyConfig.size.push(sizeX);
  76985. bodyConfig.size.push(sizeY);
  76986. bodyConfig.size.push(sizeZ);
  76987. break;
  76988. }
  76989. //actually not needed, but hey...
  76990. i.object.rotationQuaternion = oldQuaternion;
  76991. });
  76992. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76993. }
  76994. else {
  76995. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76996. }
  76997. impostor.setDeltaPosition(this._tmpPositionVector);
  76998. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76999. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77000. };
  77001. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77002. //impostor.physicsBody.dispose();
  77003. //Same as : (older oimo versions)
  77004. this.world.removeRigidBody(impostor.physicsBody);
  77005. };
  77006. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77007. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77008. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77009. if (!mainBody || !connectedBody) {
  77010. return;
  77011. }
  77012. var jointData = impostorJoint.joint.jointData;
  77013. var options = jointData.nativeParams || {};
  77014. var type;
  77015. var nativeJointData = {
  77016. body1: mainBody,
  77017. body2: connectedBody,
  77018. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77019. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77020. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77021. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77022. min: options.min,
  77023. max: options.max,
  77024. collision: options.collision || jointData.collision,
  77025. spring: options.spring,
  77026. //supporting older version of Oimo
  77027. world: this.world
  77028. };
  77029. switch (impostorJoint.joint.type) {
  77030. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77031. type = "jointBall";
  77032. break;
  77033. case BABYLON.PhysicsJoint.SpringJoint:
  77034. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77035. var springData = jointData;
  77036. nativeJointData.min = springData.length || nativeJointData.min;
  77037. //Max should also be set, just make sure it is at least min
  77038. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77039. case BABYLON.PhysicsJoint.DistanceJoint:
  77040. type = "jointDistance";
  77041. nativeJointData.max = jointData.maxDistance;
  77042. break;
  77043. case BABYLON.PhysicsJoint.PrismaticJoint:
  77044. type = "jointPrisme";
  77045. break;
  77046. case BABYLON.PhysicsJoint.SliderJoint:
  77047. type = "jointSlide";
  77048. break;
  77049. case BABYLON.PhysicsJoint.WheelJoint:
  77050. type = "jointWheel";
  77051. break;
  77052. case BABYLON.PhysicsJoint.HingeJoint:
  77053. default:
  77054. type = "jointHinge";
  77055. break;
  77056. }
  77057. nativeJointData.type = type;
  77058. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77059. };
  77060. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77061. //Bug in Oimo prevents us from disposing a joint in the playground
  77062. //joint.joint.physicsJoint.dispose();
  77063. //So we will bruteforce it!
  77064. try {
  77065. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77066. }
  77067. catch (e) {
  77068. BABYLON.Tools.Warn(e);
  77069. }
  77070. };
  77071. OimoJSPlugin.prototype.isSupported = function () {
  77072. return this.BJSOIMO !== undefined;
  77073. };
  77074. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77075. if (!impostor.physicsBody.sleeping) {
  77076. //TODO check that
  77077. if (impostor.physicsBody.shapes.next) {
  77078. var parentShape = this._getLastShape(impostor.physicsBody);
  77079. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77080. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77081. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77082. }
  77083. else {
  77084. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77085. }
  77086. if (impostor.object.rotationQuaternion) {
  77087. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77088. impostor.object.rotationQuaternion.normalize();
  77089. }
  77090. }
  77091. };
  77092. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77093. var body = impostor.physicsBody;
  77094. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77095. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77096. body.syncShapes();
  77097. body.awake();
  77098. };
  77099. OimoJSPlugin.prototype._getLastShape = function (body) {
  77100. var lastShape = body.shapes;
  77101. while (lastShape.next) {
  77102. lastShape = lastShape.next;
  77103. }
  77104. return lastShape;
  77105. };
  77106. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77107. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77108. };
  77109. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77110. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77111. };
  77112. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77113. var v = impostor.physicsBody.linearVelocity;
  77114. if (!v) {
  77115. return null;
  77116. }
  77117. return new BABYLON.Vector3(v.x, v.y, v.z);
  77118. };
  77119. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77120. var v = impostor.physicsBody.angularVelocity;
  77121. if (!v) {
  77122. return null;
  77123. }
  77124. return new BABYLON.Vector3(v.x, v.y, v.z);
  77125. };
  77126. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77127. var staticBody = mass === 0;
  77128. //this will actually set the body's density and not its mass.
  77129. //But this is how oimo treats the mass variable.
  77130. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77131. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77132. };
  77133. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77134. return impostor.physicsBody.shapes.density;
  77135. };
  77136. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77137. return impostor.physicsBody.shapes.friction;
  77138. };
  77139. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77140. impostor.physicsBody.shapes.friction = friction;
  77141. };
  77142. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77143. return impostor.physicsBody.shapes.restitution;
  77144. };
  77145. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77146. impostor.physicsBody.shapes.restitution = restitution;
  77147. };
  77148. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77149. impostor.physicsBody.sleep();
  77150. };
  77151. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77152. impostor.physicsBody.awake();
  77153. };
  77154. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77155. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77156. if (minDistance !== void 0) {
  77157. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77158. }
  77159. };
  77160. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77161. //TODO separate rotational and transational motors.
  77162. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77163. if (motor) {
  77164. motor.setMotor(speed, maxForce);
  77165. }
  77166. };
  77167. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77168. //TODO separate rotational and transational motors.
  77169. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77170. if (motor) {
  77171. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77172. }
  77173. };
  77174. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77175. var body = impostor.physicsBody;
  77176. mesh.position.x = body.position.x;
  77177. mesh.position.y = body.position.y;
  77178. mesh.position.z = body.position.z;
  77179. if (mesh.rotationQuaternion) {
  77180. mesh.rotationQuaternion.x = body.orientation.x;
  77181. mesh.rotationQuaternion.y = body.orientation.y;
  77182. mesh.rotationQuaternion.z = body.orientation.z;
  77183. mesh.rotationQuaternion.w = body.orientation.s;
  77184. }
  77185. };
  77186. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77187. return impostor.physicsBody.shapes.radius;
  77188. };
  77189. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77190. var shape = impostor.physicsBody.shapes;
  77191. result.x = shape.halfWidth * 2;
  77192. result.y = shape.halfHeight * 2;
  77193. result.z = shape.halfDepth * 2;
  77194. };
  77195. OimoJSPlugin.prototype.dispose = function () {
  77196. this.world.clear();
  77197. };
  77198. return OimoJSPlugin;
  77199. }());
  77200. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77201. })(BABYLON || (BABYLON = {}));
  77202. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77203. var BABYLON;
  77204. (function (BABYLON) {
  77205. /*
  77206. * Based on jsTGALoader - Javascript loader for TGA file
  77207. * By Vincent Thibault
  77208. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77209. */
  77210. var TGATools = /** @class */ (function () {
  77211. function TGATools() {
  77212. }
  77213. TGATools.GetTGAHeader = function (data) {
  77214. var offset = 0;
  77215. var header = {
  77216. id_length: data[offset++],
  77217. colormap_type: data[offset++],
  77218. image_type: data[offset++],
  77219. colormap_index: data[offset++] | data[offset++] << 8,
  77220. colormap_length: data[offset++] | data[offset++] << 8,
  77221. colormap_size: data[offset++],
  77222. origin: [
  77223. data[offset++] | data[offset++] << 8,
  77224. data[offset++] | data[offset++] << 8
  77225. ],
  77226. width: data[offset++] | data[offset++] << 8,
  77227. height: data[offset++] | data[offset++] << 8,
  77228. pixel_size: data[offset++],
  77229. flags: data[offset++]
  77230. };
  77231. return header;
  77232. };
  77233. TGATools.UploadContent = function (gl, data) {
  77234. // Not enough data to contain header ?
  77235. if (data.length < 19) {
  77236. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77237. return;
  77238. }
  77239. // Read Header
  77240. var offset = 18;
  77241. var header = TGATools.GetTGAHeader(data);
  77242. // Assume it's a valid Targa file.
  77243. if (header.id_length + offset > data.length) {
  77244. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77245. return;
  77246. }
  77247. // Skip not needed data
  77248. offset += header.id_length;
  77249. var use_rle = false;
  77250. var use_pal = false;
  77251. var use_grey = false;
  77252. // Get some informations.
  77253. switch (header.image_type) {
  77254. case TGATools._TYPE_RLE_INDEXED:
  77255. use_rle = true;
  77256. case TGATools._TYPE_INDEXED:
  77257. use_pal = true;
  77258. break;
  77259. case TGATools._TYPE_RLE_RGB:
  77260. use_rle = true;
  77261. case TGATools._TYPE_RGB:
  77262. // use_rgb = true;
  77263. break;
  77264. case TGATools._TYPE_RLE_GREY:
  77265. use_rle = true;
  77266. case TGATools._TYPE_GREY:
  77267. use_grey = true;
  77268. break;
  77269. }
  77270. var pixel_data;
  77271. // var numAlphaBits = header.flags & 0xf;
  77272. var pixel_size = header.pixel_size >> 3;
  77273. var pixel_total = header.width * header.height * pixel_size;
  77274. // Read palettes
  77275. var palettes;
  77276. if (use_pal) {
  77277. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77278. }
  77279. // Read LRE
  77280. if (use_rle) {
  77281. pixel_data = new Uint8Array(pixel_total);
  77282. var c, count, i;
  77283. var localOffset = 0;
  77284. var pixels = new Uint8Array(pixel_size);
  77285. while (offset < pixel_total && localOffset < pixel_total) {
  77286. c = data[offset++];
  77287. count = (c & 0x7f) + 1;
  77288. // RLE pixels
  77289. if (c & 0x80) {
  77290. // Bind pixel tmp array
  77291. for (i = 0; i < pixel_size; ++i) {
  77292. pixels[i] = data[offset++];
  77293. }
  77294. // Copy pixel array
  77295. for (i = 0; i < count; ++i) {
  77296. pixel_data.set(pixels, localOffset + i * pixel_size);
  77297. }
  77298. localOffset += pixel_size * count;
  77299. }
  77300. else {
  77301. count *= pixel_size;
  77302. for (i = 0; i < count; ++i) {
  77303. pixel_data[localOffset + i] = data[offset++];
  77304. }
  77305. localOffset += count;
  77306. }
  77307. }
  77308. }
  77309. else {
  77310. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77311. }
  77312. // Load to texture
  77313. var x_start, y_start, x_step, y_step, y_end, x_end;
  77314. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77315. default:
  77316. case TGATools._ORIGIN_UL:
  77317. x_start = 0;
  77318. x_step = 1;
  77319. x_end = header.width;
  77320. y_start = 0;
  77321. y_step = 1;
  77322. y_end = header.height;
  77323. break;
  77324. case TGATools._ORIGIN_BL:
  77325. x_start = 0;
  77326. x_step = 1;
  77327. x_end = header.width;
  77328. y_start = header.height - 1;
  77329. y_step = -1;
  77330. y_end = -1;
  77331. break;
  77332. case TGATools._ORIGIN_UR:
  77333. x_start = header.width - 1;
  77334. x_step = -1;
  77335. x_end = -1;
  77336. y_start = 0;
  77337. y_step = 1;
  77338. y_end = header.height;
  77339. break;
  77340. case TGATools._ORIGIN_BR:
  77341. x_start = header.width - 1;
  77342. x_step = -1;
  77343. x_end = -1;
  77344. y_start = header.height - 1;
  77345. y_step = -1;
  77346. y_end = -1;
  77347. break;
  77348. }
  77349. // Load the specify method
  77350. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77351. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77352. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77353. };
  77354. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77355. var image = pixel_data, colormap = palettes;
  77356. var width = header.width, height = header.height;
  77357. var color, i = 0, x, y;
  77358. var imageData = new Uint8Array(width * height * 4);
  77359. for (y = y_start; y !== y_end; y += y_step) {
  77360. for (x = x_start; x !== x_end; x += x_step, i++) {
  77361. color = image[i];
  77362. imageData[(x + width * y) * 4 + 3] = 255;
  77363. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77364. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77365. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77366. }
  77367. }
  77368. return imageData;
  77369. };
  77370. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77371. var image = pixel_data;
  77372. var width = header.width, height = header.height;
  77373. var color, i = 0, x, y;
  77374. var imageData = new Uint8Array(width * height * 4);
  77375. for (y = y_start; y !== y_end; y += y_step) {
  77376. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77377. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77378. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  77379. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  77380. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  77381. imageData[(x + width * y) * 4 + 0] = r;
  77382. imageData[(x + width * y) * 4 + 1] = g;
  77383. imageData[(x + width * y) * 4 + 2] = b;
  77384. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77385. }
  77386. }
  77387. return imageData;
  77388. };
  77389. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77390. var image = pixel_data;
  77391. var width = header.width, height = header.height;
  77392. var i = 0, x, y;
  77393. var imageData = new Uint8Array(width * height * 4);
  77394. for (y = y_start; y !== y_end; y += y_step) {
  77395. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77396. imageData[(x + width * y) * 4 + 3] = 255;
  77397. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77398. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77399. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77400. }
  77401. }
  77402. return imageData;
  77403. };
  77404. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77405. var image = pixel_data;
  77406. var width = header.width, height = header.height;
  77407. var i = 0, x, y;
  77408. var imageData = new Uint8Array(width * height * 4);
  77409. for (y = y_start; y !== y_end; y += y_step) {
  77410. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77411. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77412. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77413. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77414. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77415. }
  77416. }
  77417. return imageData;
  77418. };
  77419. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77420. var image = pixel_data;
  77421. var width = header.width, height = header.height;
  77422. var color, i = 0, x, y;
  77423. var imageData = new Uint8Array(width * height * 4);
  77424. for (y = y_start; y !== y_end; y += y_step) {
  77425. for (x = x_start; x !== x_end; x += x_step, i++) {
  77426. color = image[i];
  77427. imageData[(x + width * y) * 4 + 0] = color;
  77428. imageData[(x + width * y) * 4 + 1] = color;
  77429. imageData[(x + width * y) * 4 + 2] = color;
  77430. imageData[(x + width * y) * 4 + 3] = 255;
  77431. }
  77432. }
  77433. return imageData;
  77434. };
  77435. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77436. var image = pixel_data;
  77437. var width = header.width, height = header.height;
  77438. var i = 0, x, y;
  77439. var imageData = new Uint8Array(width * height * 4);
  77440. for (y = y_start; y !== y_end; y += y_step) {
  77441. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77442. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77443. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77444. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77445. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77446. }
  77447. }
  77448. return imageData;
  77449. };
  77450. //private static _TYPE_NO_DATA = 0;
  77451. TGATools._TYPE_INDEXED = 1;
  77452. TGATools._TYPE_RGB = 2;
  77453. TGATools._TYPE_GREY = 3;
  77454. TGATools._TYPE_RLE_INDEXED = 9;
  77455. TGATools._TYPE_RLE_RGB = 10;
  77456. TGATools._TYPE_RLE_GREY = 11;
  77457. TGATools._ORIGIN_MASK = 0x30;
  77458. TGATools._ORIGIN_SHIFT = 0x04;
  77459. TGATools._ORIGIN_BL = 0x00;
  77460. TGATools._ORIGIN_BR = 0x01;
  77461. TGATools._ORIGIN_UL = 0x02;
  77462. TGATools._ORIGIN_UR = 0x03;
  77463. return TGATools;
  77464. }());
  77465. BABYLON.TGATools = TGATools;
  77466. })(BABYLON || (BABYLON = {}));
  77467. //# sourceMappingURL=babylon.tga.js.map
  77468. var BABYLON;
  77469. (function (BABYLON) {
  77470. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77471. // All values and structures referenced from:
  77472. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77473. var DDS_MAGIC = 0x20534444;
  77474. var
  77475. //DDSD_CAPS = 0x1,
  77476. //DDSD_HEIGHT = 0x2,
  77477. //DDSD_WIDTH = 0x4,
  77478. //DDSD_PITCH = 0x8,
  77479. //DDSD_PIXELFORMAT = 0x1000,
  77480. DDSD_MIPMAPCOUNT = 0x20000;
  77481. //DDSD_LINEARSIZE = 0x80000,
  77482. //DDSD_DEPTH = 0x800000;
  77483. // var DDSCAPS_COMPLEX = 0x8,
  77484. // DDSCAPS_MIPMAP = 0x400000,
  77485. // DDSCAPS_TEXTURE = 0x1000;
  77486. var DDSCAPS2_CUBEMAP = 0x200;
  77487. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77488. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77489. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77490. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77491. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77492. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77493. // DDSCAPS2_VOLUME = 0x200000;
  77494. var
  77495. //DDPF_ALPHAPIXELS = 0x1,
  77496. //DDPF_ALPHA = 0x2,
  77497. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77498. //DDPF_YUV = 0x200,
  77499. DDPF_LUMINANCE = 0x20000;
  77500. function FourCCToInt32(value) {
  77501. return value.charCodeAt(0) +
  77502. (value.charCodeAt(1) << 8) +
  77503. (value.charCodeAt(2) << 16) +
  77504. (value.charCodeAt(3) << 24);
  77505. }
  77506. function Int32ToFourCC(value) {
  77507. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77508. }
  77509. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77510. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77511. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77512. var FOURCC_DX10 = FourCCToInt32("DX10");
  77513. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77514. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77515. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77516. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77517. var headerLengthInt = 31; // The header length in 32 bit ints
  77518. // Offsets into the header array
  77519. var off_magic = 0;
  77520. var off_size = 1;
  77521. var off_flags = 2;
  77522. var off_height = 3;
  77523. var off_width = 4;
  77524. var off_mipmapCount = 7;
  77525. var off_pfFlags = 20;
  77526. var off_pfFourCC = 21;
  77527. var off_RGBbpp = 22;
  77528. var off_RMask = 23;
  77529. var off_GMask = 24;
  77530. var off_BMask = 25;
  77531. var off_AMask = 26;
  77532. // var off_caps1 = 27;
  77533. var off_caps2 = 28;
  77534. // var off_caps3 = 29;
  77535. // var off_caps4 = 30;
  77536. var off_dxgiFormat = 32;
  77537. ;
  77538. var DDSTools = /** @class */ (function () {
  77539. function DDSTools() {
  77540. }
  77541. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77542. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77543. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77544. var mipmapCount = 1;
  77545. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77546. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77547. }
  77548. var fourCC = header[off_pfFourCC];
  77549. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77550. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77551. switch (fourCC) {
  77552. case FOURCC_D3DFMT_R16G16B16A16F:
  77553. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77554. break;
  77555. case FOURCC_D3DFMT_R32G32B32A32F:
  77556. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77557. break;
  77558. case FOURCC_DX10:
  77559. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77560. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77561. break;
  77562. }
  77563. }
  77564. return {
  77565. width: header[off_width],
  77566. height: header[off_height],
  77567. mipmapCount: mipmapCount,
  77568. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77569. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77570. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77571. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77572. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77573. dxgiFormat: dxgiFormat,
  77574. textureType: textureType
  77575. };
  77576. };
  77577. DDSTools._ToHalfFloat = function (value) {
  77578. if (!DDSTools._FloatView) {
  77579. DDSTools._FloatView = new Float32Array(1);
  77580. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77581. }
  77582. DDSTools._FloatView[0] = value;
  77583. var x = DDSTools._Int32View[0];
  77584. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77585. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77586. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77587. /* If zero, or denormal, or exponent underflows too much for a denormal
  77588. * half, return signed zero. */
  77589. if (e < 103) {
  77590. return bits;
  77591. }
  77592. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77593. if (e > 142) {
  77594. bits |= 0x7c00;
  77595. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77596. * not Inf, so make sure we set one mantissa bit too. */
  77597. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77598. return bits;
  77599. }
  77600. /* If exponent underflows but not too much, return a denormal */
  77601. if (e < 113) {
  77602. m |= 0x0800;
  77603. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77604. * to 1, which is OK. */
  77605. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77606. return bits;
  77607. }
  77608. bits |= ((e - 112) << 10) | (m >> 1);
  77609. bits += m & 1;
  77610. return bits;
  77611. };
  77612. DDSTools._FromHalfFloat = function (value) {
  77613. var s = (value & 0x8000) >> 15;
  77614. var e = (value & 0x7C00) >> 10;
  77615. var f = value & 0x03FF;
  77616. if (e === 0) {
  77617. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77618. }
  77619. else if (e == 0x1F) {
  77620. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77621. }
  77622. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77623. };
  77624. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77625. var destArray = new Float32Array(dataLength);
  77626. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77627. var index = 0;
  77628. for (var y = 0; y < height; y++) {
  77629. for (var x = 0; x < width; x++) {
  77630. var srcPos = (x + y * width) * 4;
  77631. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77632. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77633. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77634. if (DDSTools.StoreLODInAlphaChannel) {
  77635. destArray[index + 3] = lod;
  77636. }
  77637. else {
  77638. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77639. }
  77640. index += 4;
  77641. }
  77642. }
  77643. return destArray;
  77644. };
  77645. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77646. if (DDSTools.StoreLODInAlphaChannel) {
  77647. var destArray = new Uint16Array(dataLength);
  77648. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77649. var index = 0;
  77650. for (var y = 0; y < height; y++) {
  77651. for (var x = 0; x < width; x++) {
  77652. var srcPos = (x + y * width) * 4;
  77653. destArray[index] = srcData[srcPos];
  77654. destArray[index + 1] = srcData[srcPos + 1];
  77655. destArray[index + 2] = srcData[srcPos + 2];
  77656. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77657. index += 4;
  77658. }
  77659. }
  77660. return destArray;
  77661. }
  77662. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77663. };
  77664. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77665. if (DDSTools.StoreLODInAlphaChannel) {
  77666. var destArray = new Float32Array(dataLength);
  77667. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77668. var index = 0;
  77669. for (var y = 0; y < height; y++) {
  77670. for (var x = 0; x < width; x++) {
  77671. var srcPos = (x + y * width) * 4;
  77672. destArray[index] = srcData[srcPos];
  77673. destArray[index + 1] = srcData[srcPos + 1];
  77674. destArray[index + 2] = srcData[srcPos + 2];
  77675. destArray[index + 3] = lod;
  77676. index += 4;
  77677. }
  77678. }
  77679. return destArray;
  77680. }
  77681. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77682. };
  77683. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77684. var destArray = new Uint8Array(dataLength);
  77685. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77686. var index = 0;
  77687. for (var y = 0; y < height; y++) {
  77688. for (var x = 0; x < width; x++) {
  77689. var srcPos = (x + y * width) * 4;
  77690. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77691. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77692. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77693. if (DDSTools.StoreLODInAlphaChannel) {
  77694. destArray[index + 3] = lod;
  77695. }
  77696. else {
  77697. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77698. }
  77699. index += 4;
  77700. }
  77701. }
  77702. return destArray;
  77703. };
  77704. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77705. var destArray = new Uint8Array(dataLength);
  77706. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77707. var index = 0;
  77708. for (var y = 0; y < height; y++) {
  77709. for (var x = 0; x < width; x++) {
  77710. var srcPos = (x + y * width) * 4;
  77711. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77712. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77713. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77714. if (DDSTools.StoreLODInAlphaChannel) {
  77715. destArray[index + 3] = lod;
  77716. }
  77717. else {
  77718. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77719. }
  77720. index += 4;
  77721. }
  77722. }
  77723. return destArray;
  77724. };
  77725. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77726. var byteArray = new Uint8Array(dataLength);
  77727. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77728. var index = 0;
  77729. for (var y = 0; y < height; y++) {
  77730. for (var x = 0; x < width; x++) {
  77731. var srcPos = (x + y * width) * 4;
  77732. byteArray[index] = srcData[srcPos + rOffset];
  77733. byteArray[index + 1] = srcData[srcPos + gOffset];
  77734. byteArray[index + 2] = srcData[srcPos + bOffset];
  77735. byteArray[index + 3] = srcData[srcPos + aOffset];
  77736. index += 4;
  77737. }
  77738. }
  77739. return byteArray;
  77740. };
  77741. DDSTools._ExtractLongWordOrder = function (value) {
  77742. if (value === 0 || value === 255 || value === -16777216) {
  77743. return 0;
  77744. }
  77745. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77746. };
  77747. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77748. var byteArray = new Uint8Array(dataLength);
  77749. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77750. var index = 0;
  77751. for (var y = 0; y < height; y++) {
  77752. for (var x = 0; x < width; x++) {
  77753. var srcPos = (x + y * width) * 3;
  77754. byteArray[index] = srcData[srcPos + rOffset];
  77755. byteArray[index + 1] = srcData[srcPos + gOffset];
  77756. byteArray[index + 2] = srcData[srcPos + bOffset];
  77757. index += 3;
  77758. }
  77759. }
  77760. return byteArray;
  77761. };
  77762. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77763. var byteArray = new Uint8Array(dataLength);
  77764. var srcData = new Uint8Array(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);
  77769. byteArray[index] = srcData[srcPos];
  77770. index++;
  77771. }
  77772. }
  77773. return byteArray;
  77774. };
  77775. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77776. if (lodIndex === void 0) { lodIndex = -1; }
  77777. var ext = engine.getCaps().s3tc;
  77778. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77779. var fourCC, width, height, dataLength = 0, dataOffset;
  77780. var byteArray, mipmapCount, mip;
  77781. var internalFormat = 0;
  77782. var format = 0;
  77783. var blockBytes = 1;
  77784. if (header[off_magic] !== DDS_MAGIC) {
  77785. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77786. return;
  77787. }
  77788. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77789. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77790. return;
  77791. }
  77792. if (info.isCompressed && !ext) {
  77793. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77794. return;
  77795. }
  77796. var bpp = header[off_RGBbpp];
  77797. dataOffset = header[off_size] + 4;
  77798. var computeFormats = false;
  77799. if (info.isFourCC) {
  77800. fourCC = header[off_pfFourCC];
  77801. switch (fourCC) {
  77802. case FOURCC_DXT1:
  77803. blockBytes = 8;
  77804. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77805. break;
  77806. case FOURCC_DXT3:
  77807. blockBytes = 16;
  77808. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77809. break;
  77810. case FOURCC_DXT5:
  77811. blockBytes = 16;
  77812. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77813. break;
  77814. case FOURCC_D3DFMT_R16G16B16A16F:
  77815. computeFormats = true;
  77816. break;
  77817. case FOURCC_D3DFMT_R32G32B32A32F:
  77818. computeFormats = true;
  77819. break;
  77820. case FOURCC_DX10:
  77821. // There is an additionnal header so dataOffset need to be changed
  77822. dataOffset += 5 * 4; // 5 uints
  77823. var supported = false;
  77824. switch (info.dxgiFormat) {
  77825. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77826. computeFormats = true;
  77827. supported = true;
  77828. break;
  77829. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77830. info.isRGB = true;
  77831. info.isFourCC = false;
  77832. bpp = 32;
  77833. supported = true;
  77834. break;
  77835. }
  77836. if (supported) {
  77837. break;
  77838. }
  77839. default:
  77840. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77841. return;
  77842. }
  77843. }
  77844. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77845. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77846. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77847. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77848. if (computeFormats) {
  77849. format = engine._getWebGLTextureType(info.textureType);
  77850. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77851. }
  77852. mipmapCount = 1;
  77853. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77854. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77855. }
  77856. for (var face = 0; face < faces; face++) {
  77857. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77858. width = header[off_width];
  77859. height = header[off_height];
  77860. for (mip = 0; mip < mipmapCount; ++mip) {
  77861. if (lodIndex === -1 || lodIndex === mip) {
  77862. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77863. var i = (lodIndex === -1) ? mip : 0;
  77864. if (!info.isCompressed && info.isFourCC) {
  77865. dataLength = width * height * 4;
  77866. var floatArray = null;
  77867. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77868. if (bpp === 128) {
  77869. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77870. }
  77871. else if (bpp === 64) {
  77872. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77873. }
  77874. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77875. format = engine._getWebGLTextureType(info.textureType);
  77876. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77877. }
  77878. else {
  77879. if (bpp === 128) {
  77880. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77881. }
  77882. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77883. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77884. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77885. format = engine._getWebGLTextureType(info.textureType);
  77886. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77887. }
  77888. else {
  77889. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77890. }
  77891. }
  77892. if (floatArray) {
  77893. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77894. }
  77895. }
  77896. else if (info.isRGB) {
  77897. if (bpp === 24) {
  77898. dataLength = width * height * 3;
  77899. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77900. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77901. }
  77902. else {
  77903. dataLength = width * height * 4;
  77904. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77905. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77906. }
  77907. }
  77908. else if (info.isLuminance) {
  77909. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77910. var unpaddedRowSize = width;
  77911. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77912. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77913. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77914. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77915. }
  77916. else {
  77917. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77918. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77919. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77920. }
  77921. }
  77922. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77923. width *= 0.5;
  77924. height *= 0.5;
  77925. width = Math.max(1.0, width);
  77926. height = Math.max(1.0, height);
  77927. }
  77928. if (currentFace !== undefined) {
  77929. // Loading a single face
  77930. break;
  77931. }
  77932. }
  77933. };
  77934. DDSTools.StoreLODInAlphaChannel = false;
  77935. return DDSTools;
  77936. }());
  77937. BABYLON.DDSTools = DDSTools;
  77938. })(BABYLON || (BABYLON = {}));
  77939. //# sourceMappingURL=babylon.dds.js.map
  77940. var BABYLON;
  77941. (function (BABYLON) {
  77942. /**
  77943. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77944. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77945. */
  77946. var KhronosTextureContainer = /** @class */ (function () {
  77947. /**
  77948. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77949. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77950. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77951. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77952. */
  77953. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77954. this.arrayBuffer = arrayBuffer;
  77955. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77956. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77957. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77958. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77959. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77960. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77961. BABYLON.Tools.Error("texture missing KTX identifier");
  77962. return;
  77963. }
  77964. // load the reset of the header in native 32 bit int
  77965. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77966. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77967. var oppositeEndianess = header[0] === 0x01020304;
  77968. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77969. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77970. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77971. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77972. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77973. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77974. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77975. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77976. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77977. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77978. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77979. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77980. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77981. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77982. if (this.glType !== 0) {
  77983. BABYLON.Tools.Error("only compressed formats currently supported");
  77984. return;
  77985. }
  77986. else {
  77987. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77988. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77989. }
  77990. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77991. BABYLON.Tools.Error("only 2D textures currently supported");
  77992. return;
  77993. }
  77994. if (this.numberOfArrayElements !== 0) {
  77995. BABYLON.Tools.Error("texture arrays not currently supported");
  77996. return;
  77997. }
  77998. if (this.numberOfFaces !== facesExpected) {
  77999. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78000. return;
  78001. }
  78002. // we now have a completely validated file, so could use existence of loadType as success
  78003. // would need to make this more elaborate & adjust checks above to support more than one load type
  78004. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78005. }
  78006. // not as fast hardware based, but will probably never need to use
  78007. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78008. return ((val & 0xFF) << 24)
  78009. | ((val & 0xFF00) << 8)
  78010. | ((val >> 8) & 0xFF00)
  78011. | ((val >> 24) & 0xFF);
  78012. };
  78013. /**
  78014. * It is assumed that the texture has already been created & is currently bound
  78015. */
  78016. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78017. switch (this.loadType) {
  78018. case KhronosTextureContainer.COMPRESSED_2D:
  78019. this._upload2DCompressedLevels(gl, loadMipmaps);
  78020. break;
  78021. case KhronosTextureContainer.TEX_2D:
  78022. case KhronosTextureContainer.COMPRESSED_3D:
  78023. case KhronosTextureContainer.TEX_3D:
  78024. }
  78025. };
  78026. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78027. // initialize width & height for level 1
  78028. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78029. var width = this.pixelWidth;
  78030. var height = this.pixelHeight;
  78031. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78032. for (var level = 0; level < mipmapCount; level++) {
  78033. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78034. for (var face = 0; face < this.numberOfFaces; face++) {
  78035. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78036. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78037. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78038. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78039. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78040. }
  78041. width = Math.max(1.0, width * 0.5);
  78042. height = Math.max(1.0, height * 0.5);
  78043. }
  78044. };
  78045. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78046. // load types
  78047. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78048. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78049. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78050. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78051. return KhronosTextureContainer;
  78052. }());
  78053. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78054. })(BABYLON || (BABYLON = {}));
  78055. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78056. var BABYLON;
  78057. (function (BABYLON) {
  78058. var Debug = /** @class */ (function () {
  78059. function Debug() {
  78060. }
  78061. Debug.AxesViewer = /** @class */ (function () {
  78062. function AxesViewer(scene, scaleLines) {
  78063. if (scaleLines === void 0) { scaleLines = 1; }
  78064. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78065. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78066. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78067. this.scaleLines = 1;
  78068. this.scaleLines = scaleLines;
  78069. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78070. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78071. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78072. this._xmesh.renderingGroupId = 2;
  78073. this._ymesh.renderingGroupId = 2;
  78074. this._zmesh.renderingGroupId = 2;
  78075. this._xmesh.material.checkReadyOnlyOnce = true;
  78076. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78077. this._ymesh.material.checkReadyOnlyOnce = true;
  78078. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78079. this._zmesh.material.checkReadyOnlyOnce = true;
  78080. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78081. this.scene = scene;
  78082. }
  78083. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78084. var scaleLines = this.scaleLines;
  78085. if (this._xmesh) {
  78086. this._xmesh.position.copyFrom(position);
  78087. }
  78088. if (this._ymesh) {
  78089. this._ymesh.position.copyFrom(position);
  78090. }
  78091. if (this._zmesh) {
  78092. this._zmesh.position.copyFrom(position);
  78093. }
  78094. var point2 = this._xline[1];
  78095. point2.x = xaxis.x * scaleLines;
  78096. point2.y = xaxis.y * scaleLines;
  78097. point2.z = xaxis.z * scaleLines;
  78098. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78099. point2 = this._yline[1];
  78100. point2.x = yaxis.x * scaleLines;
  78101. point2.y = yaxis.y * scaleLines;
  78102. point2.z = yaxis.z * scaleLines;
  78103. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78104. point2 = this._zline[1];
  78105. point2.x = zaxis.x * scaleLines;
  78106. point2.y = zaxis.y * scaleLines;
  78107. point2.z = zaxis.z * scaleLines;
  78108. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78109. };
  78110. AxesViewer.prototype.dispose = function () {
  78111. if (this._xmesh) {
  78112. this._xmesh.dispose();
  78113. }
  78114. if (this._ymesh) {
  78115. this._ymesh.dispose();
  78116. }
  78117. if (this._zmesh) {
  78118. this._zmesh.dispose();
  78119. }
  78120. this._xmesh = null;
  78121. this._ymesh = null;
  78122. this._zmesh = null;
  78123. this.scene = null;
  78124. };
  78125. return AxesViewer;
  78126. }());
  78127. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78128. __extends(BoneAxesViewer, _super);
  78129. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78130. if (scaleLines === void 0) { scaleLines = 1; }
  78131. var _this = _super.call(this, scene, scaleLines) || this;
  78132. _this.pos = BABYLON.Vector3.Zero();
  78133. _this.xaxis = BABYLON.Vector3.Zero();
  78134. _this.yaxis = BABYLON.Vector3.Zero();
  78135. _this.zaxis = BABYLON.Vector3.Zero();
  78136. _this.mesh = mesh;
  78137. _this.bone = bone;
  78138. return _this;
  78139. }
  78140. BoneAxesViewer.prototype.update = function () {
  78141. if (!this.mesh || !this.bone) {
  78142. return;
  78143. }
  78144. var bone = this.bone;
  78145. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78146. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78147. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78148. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78149. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78150. };
  78151. BoneAxesViewer.prototype.dispose = function () {
  78152. if (this.mesh) {
  78153. this.mesh = null;
  78154. this.bone = null;
  78155. _super.prototype.dispose.call(this);
  78156. }
  78157. };
  78158. return BoneAxesViewer;
  78159. }(Debug.AxesViewer));
  78160. Debug.PhysicsViewer = /** @class */ (function () {
  78161. function PhysicsViewer(scene) {
  78162. this._impostors = [];
  78163. this._meshes = [];
  78164. this._numMeshes = 0;
  78165. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78166. var physicEngine = this._scene.getPhysicsEngine();
  78167. if (physicEngine) {
  78168. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78169. }
  78170. }
  78171. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78172. var plugin = this._physicsEnginePlugin;
  78173. for (var i = 0; i < this._numMeshes; i++) {
  78174. var impostor = this._impostors[i];
  78175. if (!impostor) {
  78176. continue;
  78177. }
  78178. if (impostor.isDisposed) {
  78179. this.hideImpostor(this._impostors[i--]);
  78180. }
  78181. else {
  78182. var mesh = this._meshes[i];
  78183. if (mesh && plugin) {
  78184. plugin.syncMeshWithImpostor(mesh, impostor);
  78185. }
  78186. }
  78187. }
  78188. };
  78189. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78190. if (!this._scene) {
  78191. return;
  78192. }
  78193. for (var i = 0; i < this._numMeshes; i++) {
  78194. if (this._impostors[i] == impostor) {
  78195. return;
  78196. }
  78197. }
  78198. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78199. if (debugMesh) {
  78200. this._impostors[this._numMeshes] = impostor;
  78201. this._meshes[this._numMeshes] = debugMesh;
  78202. if (this._numMeshes === 0) {
  78203. this._renderFunction = this._updateDebugMeshes.bind(this);
  78204. this._scene.registerBeforeRender(this._renderFunction);
  78205. }
  78206. this._numMeshes++;
  78207. }
  78208. };
  78209. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78210. if (!impostor || !this._scene) {
  78211. return;
  78212. }
  78213. var removed = false;
  78214. for (var i = 0; i < this._numMeshes; i++) {
  78215. if (this._impostors[i] == impostor) {
  78216. var mesh = this._meshes[i];
  78217. if (!mesh) {
  78218. continue;
  78219. }
  78220. this._scene.removeMesh(mesh);
  78221. mesh.dispose();
  78222. this._numMeshes--;
  78223. if (this._numMeshes > 0) {
  78224. this._meshes[i] = this._meshes[this._numMeshes];
  78225. this._impostors[i] = this._impostors[this._numMeshes];
  78226. this._meshes[this._numMeshes] = null;
  78227. this._impostors[this._numMeshes] = null;
  78228. }
  78229. else {
  78230. this._meshes[0] = null;
  78231. this._impostors[0] = null;
  78232. }
  78233. removed = true;
  78234. break;
  78235. }
  78236. }
  78237. if (removed && this._numMeshes === 0) {
  78238. this._scene.unregisterBeforeRender(this._renderFunction);
  78239. }
  78240. };
  78241. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78242. if (!this._debugMaterial) {
  78243. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78244. this._debugMaterial.wireframe = true;
  78245. }
  78246. return this._debugMaterial;
  78247. };
  78248. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78249. if (!this._debugBoxMesh) {
  78250. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78251. this._debugBoxMesh.renderingGroupId = 1;
  78252. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78253. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78254. scene.removeMesh(this._debugBoxMesh);
  78255. }
  78256. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78257. };
  78258. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78259. if (!this._debugSphereMesh) {
  78260. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78261. this._debugSphereMesh.renderingGroupId = 1;
  78262. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78263. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78264. scene.removeMesh(this._debugSphereMesh);
  78265. }
  78266. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78267. };
  78268. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78269. var mesh = null;
  78270. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78271. mesh = this._getDebugBoxMesh(scene);
  78272. impostor.getBoxSizeToRef(mesh.scaling);
  78273. }
  78274. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78275. mesh = this._getDebugSphereMesh(scene);
  78276. var radius = impostor.getRadius();
  78277. mesh.scaling.x = radius * 2;
  78278. mesh.scaling.y = radius * 2;
  78279. mesh.scaling.z = radius * 2;
  78280. }
  78281. return mesh;
  78282. };
  78283. PhysicsViewer.prototype.dispose = function () {
  78284. for (var i = 0; i < this._numMeshes; i++) {
  78285. this.hideImpostor(this._impostors[i]);
  78286. }
  78287. if (this._debugBoxMesh) {
  78288. this._debugBoxMesh.dispose();
  78289. }
  78290. if (this._debugSphereMesh) {
  78291. this._debugSphereMesh.dispose();
  78292. }
  78293. if (this._debugMaterial) {
  78294. this._debugMaterial.dispose();
  78295. }
  78296. this._impostors.length = 0;
  78297. this._scene = null;
  78298. this._physicsEnginePlugin = null;
  78299. };
  78300. return PhysicsViewer;
  78301. }());
  78302. Debug.SkeletonViewer = /** @class */ (function () {
  78303. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78304. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78305. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78306. this.skeleton = skeleton;
  78307. this.mesh = mesh;
  78308. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78309. this.renderingGroupId = renderingGroupId;
  78310. this.color = BABYLON.Color3.White();
  78311. this._debugLines = new Array();
  78312. this._isEnabled = false;
  78313. this._scene = scene;
  78314. this.update();
  78315. this._renderFunction = this.update.bind(this);
  78316. }
  78317. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78318. get: function () {
  78319. return this._isEnabled;
  78320. },
  78321. set: function (value) {
  78322. if (this._isEnabled === value) {
  78323. return;
  78324. }
  78325. this._isEnabled = value;
  78326. if (value) {
  78327. this._scene.registerBeforeRender(this._renderFunction);
  78328. }
  78329. else {
  78330. this._scene.unregisterBeforeRender(this._renderFunction);
  78331. }
  78332. },
  78333. enumerable: true,
  78334. configurable: true
  78335. });
  78336. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78337. if (x === void 0) { x = 0; }
  78338. if (y === void 0) { y = 0; }
  78339. if (z === void 0) { z = 0; }
  78340. var tmat = BABYLON.Tmp.Matrix[0];
  78341. var parentBone = bone.getParent();
  78342. tmat.copyFrom(bone.getLocalMatrix());
  78343. if (x !== 0 || y !== 0 || z !== 0) {
  78344. var tmat2 = BABYLON.Tmp.Matrix[1];
  78345. BABYLON.Matrix.IdentityToRef(tmat2);
  78346. tmat2.m[12] = x;
  78347. tmat2.m[13] = y;
  78348. tmat2.m[14] = z;
  78349. tmat2.multiplyToRef(tmat, tmat);
  78350. }
  78351. if (parentBone) {
  78352. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78353. }
  78354. tmat.multiplyToRef(meshMat, tmat);
  78355. position.x = tmat.m[12];
  78356. position.y = tmat.m[13];
  78357. position.z = tmat.m[14];
  78358. };
  78359. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78360. var len = bones.length;
  78361. var meshPos = this.mesh.position;
  78362. for (var i = 0; i < len; i++) {
  78363. var bone = bones[i];
  78364. var points = this._debugLines[i];
  78365. if (!points) {
  78366. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78367. this._debugLines[i] = points;
  78368. }
  78369. this._getBonePosition(points[0], bone, meshMat);
  78370. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78371. points[0].subtractInPlace(meshPos);
  78372. points[1].subtractInPlace(meshPos);
  78373. }
  78374. };
  78375. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78376. var len = bones.length;
  78377. var boneNum = 0;
  78378. var meshPos = this.mesh.position;
  78379. for (var i = len - 1; i >= 0; i--) {
  78380. var childBone = bones[i];
  78381. var parentBone = childBone.getParent();
  78382. if (!parentBone) {
  78383. continue;
  78384. }
  78385. var points = this._debugLines[boneNum];
  78386. if (!points) {
  78387. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78388. this._debugLines[boneNum] = points;
  78389. }
  78390. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78391. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78392. points[0].subtractInPlace(meshPos);
  78393. points[1].subtractInPlace(meshPos);
  78394. boneNum++;
  78395. }
  78396. };
  78397. SkeletonViewer.prototype.update = function () {
  78398. if (this.autoUpdateBonesMatrices) {
  78399. this.skeleton.computeAbsoluteTransforms();
  78400. }
  78401. if (this.skeleton.bones[0].length === undefined) {
  78402. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78403. }
  78404. else {
  78405. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78406. }
  78407. if (!this._debugMesh) {
  78408. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78409. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78410. }
  78411. else {
  78412. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78413. }
  78414. this._debugMesh.position.copyFrom(this.mesh.position);
  78415. this._debugMesh.color = this.color;
  78416. };
  78417. SkeletonViewer.prototype.dispose = function () {
  78418. if (this._debugMesh) {
  78419. this.isEnabled = false;
  78420. this._debugMesh.dispose();
  78421. this._debugMesh = null;
  78422. }
  78423. };
  78424. return SkeletonViewer;
  78425. }());
  78426. return Debug;
  78427. }());
  78428. BABYLON.Debug = Debug;
  78429. })(BABYLON || (BABYLON = {}));
  78430. //# sourceMappingURL=babylon.debugModules.js.map
  78431. var BABYLON;
  78432. (function (BABYLON) {
  78433. var RayHelper = /** @class */ (function () {
  78434. function RayHelper(ray) {
  78435. this.ray = ray;
  78436. }
  78437. RayHelper.CreateAndShow = function (ray, scene, color) {
  78438. var helper = new RayHelper(ray);
  78439. helper.show(scene, color);
  78440. return helper;
  78441. };
  78442. RayHelper.prototype.show = function (scene, color) {
  78443. if (!this._renderFunction && this.ray) {
  78444. var ray = this.ray;
  78445. this._renderFunction = this._render.bind(this);
  78446. this._scene = scene;
  78447. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78448. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78449. if (this._renderFunction) {
  78450. this._scene.registerBeforeRender(this._renderFunction);
  78451. }
  78452. }
  78453. if (color && this._renderLine) {
  78454. this._renderLine.color.copyFrom(color);
  78455. }
  78456. };
  78457. RayHelper.prototype.hide = function () {
  78458. if (this._renderFunction && this._scene) {
  78459. this._scene.unregisterBeforeRender(this._renderFunction);
  78460. this._scene = null;
  78461. this._renderFunction = null;
  78462. if (this._renderLine) {
  78463. this._renderLine.dispose();
  78464. this._renderLine = null;
  78465. }
  78466. this._renderPoints = [];
  78467. }
  78468. };
  78469. RayHelper.prototype._render = function () {
  78470. var ray = this.ray;
  78471. if (!ray) {
  78472. return;
  78473. }
  78474. var point = this._renderPoints[1];
  78475. var len = Math.min(ray.length, 1000000);
  78476. point.copyFrom(ray.direction);
  78477. point.scaleInPlace(len);
  78478. point.addInPlace(ray.origin);
  78479. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78480. };
  78481. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78482. this._attachedToMesh = mesh;
  78483. var ray = this.ray;
  78484. if (!ray) {
  78485. return;
  78486. }
  78487. if (!ray.direction) {
  78488. ray.direction = BABYLON.Vector3.Zero();
  78489. }
  78490. if (!ray.origin) {
  78491. ray.origin = BABYLON.Vector3.Zero();
  78492. }
  78493. if (length) {
  78494. ray.length = length;
  78495. }
  78496. if (!meshSpaceOrigin) {
  78497. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78498. }
  78499. if (!meshSpaceDirection) {
  78500. // -1 so that this will work with Mesh.lookAt
  78501. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78502. }
  78503. if (!this._meshSpaceDirection) {
  78504. this._meshSpaceDirection = meshSpaceDirection.clone();
  78505. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78506. }
  78507. else {
  78508. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78509. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78510. }
  78511. if (!this._updateToMeshFunction) {
  78512. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78513. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78514. }
  78515. this._updateToMesh();
  78516. };
  78517. RayHelper.prototype.detachFromMesh = function () {
  78518. if (this._attachedToMesh) {
  78519. if (this._updateToMeshFunction) {
  78520. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78521. }
  78522. this._attachedToMesh = null;
  78523. this._updateToMeshFunction = null;
  78524. }
  78525. };
  78526. RayHelper.prototype._updateToMesh = function () {
  78527. var ray = this.ray;
  78528. if (!this._attachedToMesh || !ray) {
  78529. return;
  78530. }
  78531. if (this._attachedToMesh._isDisposed) {
  78532. this.detachFromMesh();
  78533. return;
  78534. }
  78535. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78536. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78537. };
  78538. RayHelper.prototype.dispose = function () {
  78539. this.hide();
  78540. this.detachFromMesh();
  78541. this.ray = null;
  78542. };
  78543. return RayHelper;
  78544. }());
  78545. BABYLON.RayHelper = RayHelper;
  78546. })(BABYLON || (BABYLON = {}));
  78547. //# sourceMappingURL=babylon.rayHelper.js.map
  78548. var BABYLON;
  78549. (function (BABYLON) {
  78550. // load the inspector using require, if not present in the global namespace.
  78551. var DebugLayer = /** @class */ (function () {
  78552. function DebugLayer(scene) {
  78553. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78554. this._scene = scene;
  78555. // load inspector using require, if it doesn't exist on the global namespace.
  78556. }
  78557. /** Creates the inspector window. */
  78558. DebugLayer.prototype._createInspector = function (config) {
  78559. if (config === void 0) { config = {}; }
  78560. var popup = config.popup || false;
  78561. var initialTab = config.initialTab || 0;
  78562. var parentElement = config.parentElement || null;
  78563. if (!this._inspector) {
  78564. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78565. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78566. } // else nothing to do,; instance is already existing
  78567. };
  78568. DebugLayer.prototype.isVisible = function () {
  78569. if (!this._inspector) {
  78570. return false;
  78571. }
  78572. return true;
  78573. };
  78574. DebugLayer.prototype.hide = function () {
  78575. if (this._inspector) {
  78576. try {
  78577. this._inspector.dispose();
  78578. }
  78579. catch (e) {
  78580. // If the inspector has been removed directly from the inspector tool
  78581. }
  78582. this._inspector = null;
  78583. }
  78584. };
  78585. DebugLayer.prototype.show = function (config) {
  78586. if (config === void 0) { config = {}; }
  78587. if (typeof this.BJSINSPECTOR == 'undefined') {
  78588. // Load inspector and add it to the DOM
  78589. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78590. }
  78591. else {
  78592. // Otherwise creates the inspector
  78593. this._createInspector(config);
  78594. }
  78595. };
  78596. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78597. return DebugLayer;
  78598. }());
  78599. BABYLON.DebugLayer = DebugLayer;
  78600. })(BABYLON || (BABYLON = {}));
  78601. //# sourceMappingURL=babylon.debugLayer.js.map
  78602. var BABYLON;
  78603. (function (BABYLON) {
  78604. var BoundingBoxRenderer = /** @class */ (function () {
  78605. function BoundingBoxRenderer(scene) {
  78606. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78607. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78608. this.showBackLines = true;
  78609. this.renderList = new BABYLON.SmartArray(32);
  78610. this._vertexBuffers = {};
  78611. this._scene = scene;
  78612. }
  78613. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78614. if (this._colorShader) {
  78615. return;
  78616. }
  78617. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78618. attributes: [BABYLON.VertexBuffer.PositionKind],
  78619. uniforms: ["world", "viewProjection", "color"]
  78620. });
  78621. var engine = this._scene.getEngine();
  78622. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78623. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78624. this._createIndexBuffer();
  78625. };
  78626. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78627. var engine = this._scene.getEngine();
  78628. 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]);
  78629. };
  78630. BoundingBoxRenderer.prototype._rebuild = function () {
  78631. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78632. if (vb) {
  78633. vb._rebuild();
  78634. }
  78635. this._createIndexBuffer();
  78636. };
  78637. BoundingBoxRenderer.prototype.reset = function () {
  78638. this.renderList.reset();
  78639. };
  78640. BoundingBoxRenderer.prototype.render = function () {
  78641. if (this.renderList.length === 0) {
  78642. return;
  78643. }
  78644. this._prepareRessources();
  78645. if (!this._colorShader.isReady()) {
  78646. return;
  78647. }
  78648. var engine = this._scene.getEngine();
  78649. engine.setDepthWrite(false);
  78650. this._colorShader._preBind();
  78651. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78652. var boundingBox = this.renderList.data[boundingBoxIndex];
  78653. var min = boundingBox.minimum;
  78654. var max = boundingBox.maximum;
  78655. var diff = max.subtract(min);
  78656. var median = min.add(diff.scale(0.5));
  78657. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78658. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78659. .multiply(boundingBox.getWorldMatrix());
  78660. // VBOs
  78661. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78662. if (this.showBackLines) {
  78663. // Back
  78664. engine.setDepthFunctionToGreaterOrEqual();
  78665. this._scene.resetCachedMaterial();
  78666. this._colorShader.setColor4("color", this.backColor.toColor4());
  78667. this._colorShader.bind(worldMatrix);
  78668. // Draw order
  78669. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78670. }
  78671. // Front
  78672. engine.setDepthFunctionToLess();
  78673. this._scene.resetCachedMaterial();
  78674. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78675. this._colorShader.bind(worldMatrix);
  78676. // Draw order
  78677. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78678. }
  78679. this._colorShader.unbind();
  78680. engine.setDepthFunctionToLessOrEqual();
  78681. engine.setDepthWrite(true);
  78682. };
  78683. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78684. this._prepareRessources();
  78685. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78686. return;
  78687. }
  78688. var engine = this._scene.getEngine();
  78689. engine.setDepthWrite(false);
  78690. engine.setColorWrite(false);
  78691. this._colorShader._preBind();
  78692. var boundingBox = mesh._boundingInfo.boundingBox;
  78693. var min = boundingBox.minimum;
  78694. var max = boundingBox.maximum;
  78695. var diff = max.subtract(min);
  78696. var median = min.add(diff.scale(0.5));
  78697. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78698. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78699. .multiply(boundingBox.getWorldMatrix());
  78700. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78701. engine.setDepthFunctionToLess();
  78702. this._scene.resetCachedMaterial();
  78703. this._colorShader.bind(worldMatrix);
  78704. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78705. this._colorShader.unbind();
  78706. engine.setDepthFunctionToLessOrEqual();
  78707. engine.setDepthWrite(true);
  78708. engine.setColorWrite(true);
  78709. };
  78710. BoundingBoxRenderer.prototype.dispose = function () {
  78711. if (!this._colorShader) {
  78712. return;
  78713. }
  78714. this.renderList.dispose();
  78715. this._colorShader.dispose();
  78716. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78717. if (buffer) {
  78718. buffer.dispose();
  78719. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78720. }
  78721. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78722. };
  78723. return BoundingBoxRenderer;
  78724. }());
  78725. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78726. })(BABYLON || (BABYLON = {}));
  78727. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78728. var BABYLON;
  78729. (function (BABYLON) {
  78730. var MorphTarget = /** @class */ (function () {
  78731. function MorphTarget(name, influence) {
  78732. if (influence === void 0) { influence = 0; }
  78733. this.name = name;
  78734. this.animations = new Array();
  78735. this._positions = null;
  78736. this._normals = null;
  78737. this._tangents = null;
  78738. this.onInfluenceChanged = new BABYLON.Observable();
  78739. this.influence = influence;
  78740. }
  78741. Object.defineProperty(MorphTarget.prototype, "influence", {
  78742. get: function () {
  78743. return this._influence;
  78744. },
  78745. set: function (influence) {
  78746. if (this._influence === influence) {
  78747. return;
  78748. }
  78749. var previous = this._influence;
  78750. this._influence = influence;
  78751. if (this.onInfluenceChanged.hasObservers) {
  78752. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78753. }
  78754. },
  78755. enumerable: true,
  78756. configurable: true
  78757. });
  78758. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78759. get: function () {
  78760. return !!this._positions;
  78761. },
  78762. enumerable: true,
  78763. configurable: true
  78764. });
  78765. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78766. get: function () {
  78767. return !!this._normals;
  78768. },
  78769. enumerable: true,
  78770. configurable: true
  78771. });
  78772. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78773. get: function () {
  78774. return !!this._tangents;
  78775. },
  78776. enumerable: true,
  78777. configurable: true
  78778. });
  78779. MorphTarget.prototype.setPositions = function (data) {
  78780. this._positions = data;
  78781. };
  78782. MorphTarget.prototype.getPositions = function () {
  78783. return this._positions;
  78784. };
  78785. MorphTarget.prototype.setNormals = function (data) {
  78786. this._normals = data;
  78787. };
  78788. MorphTarget.prototype.getNormals = function () {
  78789. return this._normals;
  78790. };
  78791. MorphTarget.prototype.setTangents = function (data) {
  78792. this._tangents = data;
  78793. };
  78794. MorphTarget.prototype.getTangents = function () {
  78795. return this._tangents;
  78796. };
  78797. /**
  78798. * Serializes the current target into a Serialization object.
  78799. * Returns the serialized object.
  78800. */
  78801. MorphTarget.prototype.serialize = function () {
  78802. var serializationObject = {};
  78803. serializationObject.name = this.name;
  78804. serializationObject.influence = this.influence;
  78805. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78806. if (this.hasNormals) {
  78807. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78808. }
  78809. if (this.hasTangents) {
  78810. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78811. }
  78812. // Animations
  78813. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78814. return serializationObject;
  78815. };
  78816. // Statics
  78817. MorphTarget.Parse = function (serializationObject) {
  78818. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78819. result.setPositions(serializationObject.positions);
  78820. if (serializationObject.normals) {
  78821. result.setNormals(serializationObject.normals);
  78822. }
  78823. if (serializationObject.tangents) {
  78824. result.setTangents(serializationObject.tangents);
  78825. }
  78826. // Animations
  78827. if (serializationObject.animations) {
  78828. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78829. var parsedAnimation = serializationObject.animations[animationIndex];
  78830. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78831. }
  78832. }
  78833. return result;
  78834. };
  78835. MorphTarget.FromMesh = function (mesh, name, influence) {
  78836. if (!name) {
  78837. name = mesh.name;
  78838. }
  78839. var result = new MorphTarget(name, influence);
  78840. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78841. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78842. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78843. }
  78844. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78845. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78846. }
  78847. return result;
  78848. };
  78849. return MorphTarget;
  78850. }());
  78851. BABYLON.MorphTarget = MorphTarget;
  78852. })(BABYLON || (BABYLON = {}));
  78853. //# sourceMappingURL=babylon.morphTarget.js.map
  78854. var BABYLON;
  78855. (function (BABYLON) {
  78856. var MorphTargetManager = /** @class */ (function () {
  78857. function MorphTargetManager(scene) {
  78858. if (scene === void 0) { scene = null; }
  78859. this._targets = new Array();
  78860. this._targetObservable = new Array();
  78861. this._activeTargets = new BABYLON.SmartArray(16);
  78862. this._supportsNormals = false;
  78863. this._supportsTangents = false;
  78864. this._vertexCount = 0;
  78865. this._uniqueId = 0;
  78866. this._tempInfluences = new Array();
  78867. if (!scene) {
  78868. scene = BABYLON.Engine.LastCreatedScene;
  78869. }
  78870. this._scene = scene;
  78871. if (this._scene) {
  78872. this._scene.morphTargetManagers.push(this);
  78873. this._uniqueId = this._scene.getUniqueId();
  78874. }
  78875. }
  78876. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78877. get: function () {
  78878. return this._uniqueId;
  78879. },
  78880. enumerable: true,
  78881. configurable: true
  78882. });
  78883. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78884. get: function () {
  78885. return this._vertexCount;
  78886. },
  78887. enumerable: true,
  78888. configurable: true
  78889. });
  78890. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78891. get: function () {
  78892. return this._supportsNormals;
  78893. },
  78894. enumerable: true,
  78895. configurable: true
  78896. });
  78897. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78898. get: function () {
  78899. return this._supportsTangents;
  78900. },
  78901. enumerable: true,
  78902. configurable: true
  78903. });
  78904. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78905. get: function () {
  78906. return this._targets.length;
  78907. },
  78908. enumerable: true,
  78909. configurable: true
  78910. });
  78911. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78912. get: function () {
  78913. return this._activeTargets.length;
  78914. },
  78915. enumerable: true,
  78916. configurable: true
  78917. });
  78918. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78919. get: function () {
  78920. return this._influences;
  78921. },
  78922. enumerable: true,
  78923. configurable: true
  78924. });
  78925. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78926. return this._activeTargets.data[index];
  78927. };
  78928. MorphTargetManager.prototype.getTarget = function (index) {
  78929. return this._targets[index];
  78930. };
  78931. MorphTargetManager.prototype.addTarget = function (target) {
  78932. var _this = this;
  78933. this._targets.push(target);
  78934. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78935. _this._syncActiveTargets(needUpdate);
  78936. }));
  78937. this._syncActiveTargets(true);
  78938. };
  78939. MorphTargetManager.prototype.removeTarget = function (target) {
  78940. var index = this._targets.indexOf(target);
  78941. if (index >= 0) {
  78942. this._targets.splice(index, 1);
  78943. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78944. this._syncActiveTargets(true);
  78945. }
  78946. };
  78947. /**
  78948. * Serializes the current manager into a Serialization object.
  78949. * Returns the serialized object.
  78950. */
  78951. MorphTargetManager.prototype.serialize = function () {
  78952. var serializationObject = {};
  78953. serializationObject.id = this.uniqueId;
  78954. serializationObject.targets = [];
  78955. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78956. var target = _a[_i];
  78957. serializationObject.targets.push(target.serialize());
  78958. }
  78959. return serializationObject;
  78960. };
  78961. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78962. var influenceCount = 0;
  78963. this._activeTargets.reset();
  78964. this._supportsNormals = true;
  78965. this._supportsTangents = true;
  78966. this._vertexCount = 0;
  78967. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78968. var target = _a[_i];
  78969. this._activeTargets.push(target);
  78970. this._tempInfluences[influenceCount++] = target.influence;
  78971. var positions = target.getPositions();
  78972. if (positions) {
  78973. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78974. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78975. var vertexCount = positions.length / 3;
  78976. if (this._vertexCount === 0) {
  78977. this._vertexCount = vertexCount;
  78978. }
  78979. else if (this._vertexCount !== vertexCount) {
  78980. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78981. return;
  78982. }
  78983. }
  78984. }
  78985. if (!this._influences || this._influences.length !== influenceCount) {
  78986. this._influences = new Float32Array(influenceCount);
  78987. }
  78988. for (var index = 0; index < influenceCount; index++) {
  78989. this._influences[index] = this._tempInfluences[index];
  78990. }
  78991. if (needUpdate && this._scene) {
  78992. // Flag meshes as dirty to resync with the active targets
  78993. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78994. var mesh = _c[_b];
  78995. if (mesh.morphTargetManager === this) {
  78996. mesh._syncGeometryWithMorphTargetManager();
  78997. }
  78998. }
  78999. }
  79000. };
  79001. // Statics
  79002. MorphTargetManager.Parse = function (serializationObject, scene) {
  79003. var result = new MorphTargetManager(scene);
  79004. result._uniqueId = serializationObject.id;
  79005. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79006. var targetData = _a[_i];
  79007. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79008. }
  79009. return result;
  79010. };
  79011. return MorphTargetManager;
  79012. }());
  79013. BABYLON.MorphTargetManager = MorphTargetManager;
  79014. })(BABYLON || (BABYLON = {}));
  79015. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79016. var BABYLON;
  79017. (function (BABYLON) {
  79018. var Octree = /** @class */ (function () {
  79019. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79020. if (maxDepth === void 0) { maxDepth = 2; }
  79021. this.maxDepth = maxDepth;
  79022. this.dynamicContent = new Array();
  79023. this._maxBlockCapacity = maxBlockCapacity || 64;
  79024. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79025. this._creationFunc = creationFunc;
  79026. }
  79027. // Methods
  79028. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79029. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79030. };
  79031. Octree.prototype.addMesh = function (entry) {
  79032. for (var index = 0; index < this.blocks.length; index++) {
  79033. var block = this.blocks[index];
  79034. block.addEntry(entry);
  79035. }
  79036. };
  79037. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79038. this._selectionContent.reset();
  79039. for (var index = 0; index < this.blocks.length; index++) {
  79040. var block = this.blocks[index];
  79041. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79042. }
  79043. if (allowDuplicate) {
  79044. this._selectionContent.concat(this.dynamicContent);
  79045. }
  79046. else {
  79047. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79048. }
  79049. return this._selectionContent;
  79050. };
  79051. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79052. this._selectionContent.reset();
  79053. for (var index = 0; index < this.blocks.length; index++) {
  79054. var block = this.blocks[index];
  79055. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79056. }
  79057. if (allowDuplicate) {
  79058. this._selectionContent.concat(this.dynamicContent);
  79059. }
  79060. else {
  79061. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79062. }
  79063. return this._selectionContent;
  79064. };
  79065. Octree.prototype.intersectsRay = function (ray) {
  79066. this._selectionContent.reset();
  79067. for (var index = 0; index < this.blocks.length; index++) {
  79068. var block = this.blocks[index];
  79069. block.intersectsRay(ray, this._selectionContent);
  79070. }
  79071. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79072. return this._selectionContent;
  79073. };
  79074. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79075. target.blocks = new Array();
  79076. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79077. // Segmenting space
  79078. for (var x = 0; x < 2; x++) {
  79079. for (var y = 0; y < 2; y++) {
  79080. for (var z = 0; z < 2; z++) {
  79081. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79082. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79083. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79084. block.addEntries(entries);
  79085. target.blocks.push(block);
  79086. }
  79087. }
  79088. }
  79089. };
  79090. Octree.CreationFuncForMeshes = function (entry, block) {
  79091. var boundingInfo = entry.getBoundingInfo();
  79092. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79093. block.entries.push(entry);
  79094. }
  79095. };
  79096. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79097. var boundingInfo = entry.getBoundingInfo();
  79098. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79099. block.entries.push(entry);
  79100. }
  79101. };
  79102. return Octree;
  79103. }());
  79104. BABYLON.Octree = Octree;
  79105. })(BABYLON || (BABYLON = {}));
  79106. //# sourceMappingURL=babylon.octree.js.map
  79107. var BABYLON;
  79108. (function (BABYLON) {
  79109. var OctreeBlock = /** @class */ (function () {
  79110. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79111. this.entries = new Array();
  79112. this._boundingVectors = new Array();
  79113. this._capacity = capacity;
  79114. this._depth = depth;
  79115. this._maxDepth = maxDepth;
  79116. this._creationFunc = creationFunc;
  79117. this._minPoint = minPoint;
  79118. this._maxPoint = maxPoint;
  79119. this._boundingVectors.push(minPoint.clone());
  79120. this._boundingVectors.push(maxPoint.clone());
  79121. this._boundingVectors.push(minPoint.clone());
  79122. this._boundingVectors[2].x = maxPoint.x;
  79123. this._boundingVectors.push(minPoint.clone());
  79124. this._boundingVectors[3].y = maxPoint.y;
  79125. this._boundingVectors.push(minPoint.clone());
  79126. this._boundingVectors[4].z = maxPoint.z;
  79127. this._boundingVectors.push(maxPoint.clone());
  79128. this._boundingVectors[5].z = minPoint.z;
  79129. this._boundingVectors.push(maxPoint.clone());
  79130. this._boundingVectors[6].x = minPoint.x;
  79131. this._boundingVectors.push(maxPoint.clone());
  79132. this._boundingVectors[7].y = minPoint.y;
  79133. }
  79134. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79135. // Property
  79136. get: function () {
  79137. return this._capacity;
  79138. },
  79139. enumerable: true,
  79140. configurable: true
  79141. });
  79142. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79143. get: function () {
  79144. return this._minPoint;
  79145. },
  79146. enumerable: true,
  79147. configurable: true
  79148. });
  79149. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79150. get: function () {
  79151. return this._maxPoint;
  79152. },
  79153. enumerable: true,
  79154. configurable: true
  79155. });
  79156. // Methods
  79157. OctreeBlock.prototype.addEntry = function (entry) {
  79158. if (this.blocks) {
  79159. for (var index = 0; index < this.blocks.length; index++) {
  79160. var block = this.blocks[index];
  79161. block.addEntry(entry);
  79162. }
  79163. return;
  79164. }
  79165. this._creationFunc(entry, this);
  79166. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79167. this.createInnerBlocks();
  79168. }
  79169. };
  79170. OctreeBlock.prototype.addEntries = function (entries) {
  79171. for (var index = 0; index < entries.length; index++) {
  79172. var mesh = entries[index];
  79173. this.addEntry(mesh);
  79174. }
  79175. };
  79176. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79177. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79178. if (this.blocks) {
  79179. for (var index = 0; index < this.blocks.length; index++) {
  79180. var block = this.blocks[index];
  79181. block.select(frustumPlanes, selection, allowDuplicate);
  79182. }
  79183. return;
  79184. }
  79185. if (allowDuplicate) {
  79186. selection.concat(this.entries);
  79187. }
  79188. else {
  79189. selection.concatWithNoDuplicate(this.entries);
  79190. }
  79191. }
  79192. };
  79193. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79194. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79195. if (this.blocks) {
  79196. for (var index = 0; index < this.blocks.length; index++) {
  79197. var block = this.blocks[index];
  79198. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79199. }
  79200. return;
  79201. }
  79202. if (allowDuplicate) {
  79203. selection.concat(this.entries);
  79204. }
  79205. else {
  79206. selection.concatWithNoDuplicate(this.entries);
  79207. }
  79208. }
  79209. };
  79210. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79211. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79212. if (this.blocks) {
  79213. for (var index = 0; index < this.blocks.length; index++) {
  79214. var block = this.blocks[index];
  79215. block.intersectsRay(ray, selection);
  79216. }
  79217. return;
  79218. }
  79219. selection.concatWithNoDuplicate(this.entries);
  79220. }
  79221. };
  79222. OctreeBlock.prototype.createInnerBlocks = function () {
  79223. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79224. };
  79225. return OctreeBlock;
  79226. }());
  79227. BABYLON.OctreeBlock = OctreeBlock;
  79228. })(BABYLON || (BABYLON = {}));
  79229. //# sourceMappingURL=babylon.octreeBlock.js.map
  79230. var BABYLON;
  79231. (function (BABYLON) {
  79232. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79233. __extends(VRDistortionCorrectionPostProcess, _super);
  79234. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79235. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79236. 'LensCenter',
  79237. 'Scale',
  79238. 'ScaleIn',
  79239. 'HmdWarpParam'
  79240. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79241. _this._isRightEye = isRightEye;
  79242. _this._distortionFactors = vrMetrics.distortionK;
  79243. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79244. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79245. _this.adaptScaleToCurrentViewport = true;
  79246. _this.onSizeChangedObservable.add(function () {
  79247. _this.aspectRatio = _this.width * .5 / _this.height;
  79248. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79249. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79250. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79251. });
  79252. _this.onApplyObservable.add(function (effect) {
  79253. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79254. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79255. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79256. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79257. });
  79258. return _this;
  79259. }
  79260. return VRDistortionCorrectionPostProcess;
  79261. }(BABYLON.PostProcess));
  79262. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79263. })(BABYLON || (BABYLON = {}));
  79264. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79265. var BABYLON;
  79266. (function (BABYLON) {
  79267. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79268. __extends(AnaglyphPostProcess, _super);
  79269. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79270. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79271. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79272. _this.onApplyObservable.add(function (effect) {
  79273. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79274. });
  79275. return _this;
  79276. }
  79277. return AnaglyphPostProcess;
  79278. }(BABYLON.PostProcess));
  79279. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79280. })(BABYLON || (BABYLON = {}));
  79281. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79282. var BABYLON;
  79283. (function (BABYLON) {
  79284. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79285. __extends(StereoscopicInterlacePostProcess, _super);
  79286. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79287. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79288. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79289. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79290. _this.onSizeChangedObservable.add(function () {
  79291. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79292. });
  79293. _this.onApplyObservable.add(function (effect) {
  79294. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79295. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79296. });
  79297. return _this;
  79298. }
  79299. return StereoscopicInterlacePostProcess;
  79300. }(BABYLON.PostProcess));
  79301. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79302. })(BABYLON || (BABYLON = {}));
  79303. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79304. var BABYLON;
  79305. (function (BABYLON) {
  79306. /**
  79307. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79308. * Screen rotation is taken into account.
  79309. */
  79310. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79311. function FreeCameraDeviceOrientationInput() {
  79312. var _this = this;
  79313. this._screenOrientationAngle = 0;
  79314. this._screenQuaternion = new BABYLON.Quaternion();
  79315. this._alpha = 0;
  79316. this._beta = 0;
  79317. this._gamma = 0;
  79318. this._orientationChanged = function () {
  79319. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79320. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79321. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79322. };
  79323. this._deviceOrientation = function (evt) {
  79324. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79325. _this._beta = evt.beta !== null ? evt.beta : 0;
  79326. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79327. };
  79328. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79329. this._orientationChanged();
  79330. }
  79331. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79332. get: function () {
  79333. return this._camera;
  79334. },
  79335. set: function (camera) {
  79336. this._camera = camera;
  79337. if (this._camera != null && !this._camera.rotationQuaternion) {
  79338. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79339. }
  79340. },
  79341. enumerable: true,
  79342. configurable: true
  79343. });
  79344. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79345. window.addEventListener("orientationchange", this._orientationChanged);
  79346. window.addEventListener("deviceorientation", this._deviceOrientation);
  79347. //In certain cases, the attach control is called AFTER orientation was changed,
  79348. //So this is needed.
  79349. this._orientationChanged();
  79350. };
  79351. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79352. window.removeEventListener("orientationchange", this._orientationChanged);
  79353. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79354. };
  79355. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79356. //if no device orientation provided, don't update the rotation.
  79357. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79358. if (!this._alpha)
  79359. return;
  79360. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79361. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79362. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79363. //Mirror on XY Plane
  79364. this._camera.rotationQuaternion.z *= -1;
  79365. this._camera.rotationQuaternion.w *= -1;
  79366. };
  79367. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79368. return "FreeCameraDeviceOrientationInput";
  79369. };
  79370. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79371. return "deviceOrientation";
  79372. };
  79373. return FreeCameraDeviceOrientationInput;
  79374. }());
  79375. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79376. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79377. })(BABYLON || (BABYLON = {}));
  79378. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79379. var BABYLON;
  79380. (function (BABYLON) {
  79381. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79382. function ArcRotateCameraVRDeviceOrientationInput() {
  79383. this.alphaCorrection = 1;
  79384. this.betaCorrection = 1;
  79385. this.gammaCorrection = 1;
  79386. this._alpha = 0;
  79387. this._gamma = 0;
  79388. this._dirty = false;
  79389. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79390. }
  79391. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79392. this.camera.attachControl(element, noPreventDefault);
  79393. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79394. };
  79395. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79396. if (evt.alpha !== null) {
  79397. this._alpha = +evt.alpha | 0;
  79398. }
  79399. if (evt.gamma !== null) {
  79400. this._gamma = +evt.gamma | 0;
  79401. }
  79402. this._dirty = true;
  79403. };
  79404. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79405. if (this._dirty) {
  79406. this._dirty = false;
  79407. if (this._gamma < 0) {
  79408. this._gamma = 180 + this._gamma;
  79409. }
  79410. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79411. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79412. }
  79413. };
  79414. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79415. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79416. };
  79417. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79418. return "ArcRotateCameraVRDeviceOrientationInput";
  79419. };
  79420. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79421. return "VRDeviceOrientation";
  79422. };
  79423. return ArcRotateCameraVRDeviceOrientationInput;
  79424. }());
  79425. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79426. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79427. })(BABYLON || (BABYLON = {}));
  79428. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79429. var BABYLON;
  79430. (function (BABYLON) {
  79431. var VRCameraMetrics = /** @class */ (function () {
  79432. function VRCameraMetrics() {
  79433. this.compensateDistortion = true;
  79434. }
  79435. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79436. get: function () {
  79437. return this.hResolution / (2 * this.vResolution);
  79438. },
  79439. enumerable: true,
  79440. configurable: true
  79441. });
  79442. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79443. get: function () {
  79444. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79445. },
  79446. enumerable: true,
  79447. configurable: true
  79448. });
  79449. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79450. get: function () {
  79451. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79452. var h = (4 * meters) / this.hScreenSize;
  79453. return BABYLON.Matrix.Translation(h, 0, 0);
  79454. },
  79455. enumerable: true,
  79456. configurable: true
  79457. });
  79458. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79459. get: function () {
  79460. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79461. var h = (4 * meters) / this.hScreenSize;
  79462. return BABYLON.Matrix.Translation(-h, 0, 0);
  79463. },
  79464. enumerable: true,
  79465. configurable: true
  79466. });
  79467. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79468. get: function () {
  79469. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79470. },
  79471. enumerable: true,
  79472. configurable: true
  79473. });
  79474. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79475. get: function () {
  79476. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79477. },
  79478. enumerable: true,
  79479. configurable: true
  79480. });
  79481. VRCameraMetrics.GetDefault = function () {
  79482. var result = new VRCameraMetrics();
  79483. result.hResolution = 1280;
  79484. result.vResolution = 800;
  79485. result.hScreenSize = 0.149759993;
  79486. result.vScreenSize = 0.0935999975;
  79487. result.vScreenCenter = 0.0467999987;
  79488. result.eyeToScreenDistance = 0.0410000011;
  79489. result.lensSeparationDistance = 0.0635000020;
  79490. result.interpupillaryDistance = 0.0640000030;
  79491. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79492. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79493. result.postProcessScaleFactor = 1.714605507808412;
  79494. result.lensCenterOffset = 0.151976421;
  79495. return result;
  79496. };
  79497. return VRCameraMetrics;
  79498. }());
  79499. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79500. })(BABYLON || (BABYLON = {}));
  79501. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79502. var BABYLON;
  79503. (function (BABYLON) {
  79504. /**
  79505. * This represents a WebVR camera.
  79506. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79507. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79508. */
  79509. var WebVRFreeCamera = /** @class */ (function (_super) {
  79510. __extends(WebVRFreeCamera, _super);
  79511. /**
  79512. * Instantiates a WebVRFreeCamera.
  79513. * @param name The name of the WebVRFreeCamera
  79514. * @param position The starting anchor position for the camera
  79515. * @param scene The scene the camera belongs to
  79516. * @param webVROptions a set of customizable options for the webVRCamera
  79517. */
  79518. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79519. if (webVROptions === void 0) { webVROptions = {}; }
  79520. var _this = _super.call(this, name, position, scene) || this;
  79521. _this.webVROptions = webVROptions;
  79522. /**
  79523. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79524. */
  79525. _this._vrDevice = null;
  79526. /**
  79527. * The rawPose of the vrDevice.
  79528. */
  79529. _this.rawPose = null;
  79530. _this._specsVersion = "1.1";
  79531. _this._attached = false;
  79532. _this._descendants = [];
  79533. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79534. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79535. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79536. _this._standingMatrix = null;
  79537. /**
  79538. * Represents device position in babylon space.
  79539. */
  79540. _this.devicePosition = BABYLON.Vector3.Zero();
  79541. /**
  79542. * Represents device rotation in babylon space.
  79543. */
  79544. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79545. /**
  79546. * The scale of the device to be used when translating from device space to babylon space.
  79547. */
  79548. _this.deviceScaleFactor = 1;
  79549. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79550. _this._worldToDevice = BABYLON.Matrix.Identity();
  79551. /**
  79552. * References to the webVR controllers for the vrDevice.
  79553. */
  79554. _this.controllers = [];
  79555. /**
  79556. * Emits an event when a controller is attached.
  79557. */
  79558. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79559. /**
  79560. * Emits an event when a controller's mesh has been loaded;
  79561. */
  79562. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79563. /**
  79564. * If the rig cameras be used as parent instead of this camera.
  79565. */
  79566. _this.rigParenting = true;
  79567. _this._defaultHeight = undefined;
  79568. _this._workingVector = BABYLON.Vector3.Zero();
  79569. _this._oneVector = BABYLON.Vector3.One();
  79570. _this._workingMatrix = BABYLON.Matrix.Identity();
  79571. _this._cache.position = BABYLON.Vector3.Zero();
  79572. if (webVROptions.defaultHeight) {
  79573. _this._defaultHeight = webVROptions.defaultHeight;
  79574. _this.position.y = _this._defaultHeight;
  79575. }
  79576. _this.minZ = 0.1;
  79577. //legacy support - the compensation boolean was removed.
  79578. if (arguments.length === 5) {
  79579. _this.webVROptions = arguments[4];
  79580. }
  79581. // default webVR options
  79582. if (_this.webVROptions.trackPosition == undefined) {
  79583. _this.webVROptions.trackPosition = true;
  79584. }
  79585. if (_this.webVROptions.controllerMeshes == undefined) {
  79586. _this.webVROptions.controllerMeshes = true;
  79587. }
  79588. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79589. _this.webVROptions.defaultLightingOnControllers = true;
  79590. }
  79591. _this.rotationQuaternion = new BABYLON.Quaternion();
  79592. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79593. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79594. }
  79595. //enable VR
  79596. var engine = _this.getEngine();
  79597. _this._onVREnabled = function (success) { if (success) {
  79598. _this.initControllers();
  79599. } };
  79600. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79601. engine.initWebVR().add(function (event) {
  79602. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79603. return;
  79604. }
  79605. _this._vrDevice = event.vrDisplay;
  79606. //reset the rig parameters.
  79607. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79608. if (_this._attached) {
  79609. _this.getEngine().enableVR();
  79610. }
  79611. });
  79612. if (typeof (VRFrameData) !== "undefined")
  79613. _this._frameData = new VRFrameData();
  79614. /**
  79615. * The idea behind the following lines:
  79616. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79617. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79618. * the second will not show it correctly.
  79619. *
  79620. * To solve this - each object that has the camera as parent will be added to a protected array.
  79621. * When the rig camera renders, it will take this array and set all of those to be its children.
  79622. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79623. * Amazing!
  79624. */
  79625. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79626. if (camera.parent === _this && _this.rigParenting) {
  79627. _this._descendants = _this.getDescendants(true, function (n) {
  79628. // don't take the cameras or the controllers!
  79629. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79630. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79631. return !isController && !isRigCamera;
  79632. });
  79633. _this._descendants.forEach(function (node) {
  79634. node.parent = camera;
  79635. });
  79636. }
  79637. });
  79638. scene.onAfterCameraRenderObservable.add(function (camera) {
  79639. if (camera.parent === _this && _this.rigParenting) {
  79640. _this._descendants.forEach(function (node) {
  79641. node.parent = _this;
  79642. });
  79643. }
  79644. });
  79645. return _this;
  79646. }
  79647. /**
  79648. * Gets the device distance from the ground in meters.
  79649. * @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.
  79650. */
  79651. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79652. if (this._standingMatrix) {
  79653. // Add standing matrix offset to get real offset from ground in room
  79654. this._standingMatrix.getTranslationToRef(this._workingVector);
  79655. return this._deviceRoomPosition.y + this._workingVector.y;
  79656. }
  79657. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79658. return this._defaultHeight || 0;
  79659. };
  79660. /**
  79661. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79662. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79663. */
  79664. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79665. var _this = this;
  79666. if (callback === void 0) { callback = function (bool) { }; }
  79667. // Use standing matrix if available
  79668. this.getEngine().initWebVRAsync().then(function (result) {
  79669. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79670. callback(false);
  79671. }
  79672. else {
  79673. _this._standingMatrix = new BABYLON.Matrix();
  79674. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79675. if (!_this.getScene().useRightHandedSystem) {
  79676. [2, 6, 8, 9, 14].forEach(function (num) {
  79677. if (_this._standingMatrix) {
  79678. _this._standingMatrix.m[num] *= -1;
  79679. }
  79680. });
  79681. }
  79682. callback(true);
  79683. }
  79684. });
  79685. };
  79686. /**
  79687. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79688. * @returns A promise with a boolean set to if the standing matrix is supported.
  79689. */
  79690. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79691. var _this = this;
  79692. return new Promise(function (res, rej) {
  79693. _this.useStandingMatrix(function (supported) {
  79694. res(supported);
  79695. });
  79696. });
  79697. };
  79698. /**
  79699. * Disposes the camera
  79700. */
  79701. WebVRFreeCamera.prototype.dispose = function () {
  79702. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79703. _super.prototype.dispose.call(this);
  79704. };
  79705. /**
  79706. * Gets a vrController by name.
  79707. * @param name The name of the controller to retreive
  79708. * @returns the controller matching the name specified or null if not found
  79709. */
  79710. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79711. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79712. var gp = _a[_i];
  79713. if (gp.hand === name) {
  79714. return gp;
  79715. }
  79716. }
  79717. return null;
  79718. };
  79719. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79720. /**
  79721. * The controller corrisponding to the users left hand.
  79722. */
  79723. get: function () {
  79724. if (!this._leftController) {
  79725. this._leftController = this.getControllerByName("left");
  79726. }
  79727. return this._leftController;
  79728. },
  79729. enumerable: true,
  79730. configurable: true
  79731. });
  79732. ;
  79733. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79734. /**
  79735. * The controller corrisponding to the users right hand.
  79736. */
  79737. get: function () {
  79738. if (!this._rightController) {
  79739. this._rightController = this.getControllerByName("right");
  79740. }
  79741. return this._rightController;
  79742. },
  79743. enumerable: true,
  79744. configurable: true
  79745. });
  79746. ;
  79747. /**
  79748. * Casts a ray forward from the vrCamera's gaze.
  79749. * @param length Length of the ray (default: 100)
  79750. * @returns the ray corrisponding to the gaze
  79751. */
  79752. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79753. if (length === void 0) { length = 100; }
  79754. if (this.leftCamera) {
  79755. // Use left eye to avoid computation to compute center on every call
  79756. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79757. }
  79758. else {
  79759. return _super.prototype.getForwardRay.call(this, length);
  79760. }
  79761. };
  79762. /**
  79763. * Updates the camera based on device's frame data
  79764. */
  79765. WebVRFreeCamera.prototype._checkInputs = function () {
  79766. if (this._vrDevice && this._vrDevice.isPresenting) {
  79767. this._vrDevice.getFrameData(this._frameData);
  79768. this.updateFromDevice(this._frameData.pose);
  79769. }
  79770. _super.prototype._checkInputs.call(this);
  79771. };
  79772. /**
  79773. * Updates the poseControlled values based on the input device pose.
  79774. * @param poseData Pose coming from the device
  79775. */
  79776. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79777. if (poseData && poseData.orientation) {
  79778. this.rawPose = poseData;
  79779. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79780. if (this.getScene().useRightHandedSystem) {
  79781. this._deviceRoomRotationQuaternion.z *= -1;
  79782. this._deviceRoomRotationQuaternion.w *= -1;
  79783. }
  79784. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79785. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79786. if (this.getScene().useRightHandedSystem) {
  79787. this._deviceRoomPosition.z *= -1;
  79788. }
  79789. }
  79790. }
  79791. };
  79792. /**
  79793. * WebVR's attach control will start broadcasting frames to the device.
  79794. * Note that in certain browsers (chrome for example) this function must be called
  79795. * within a user-interaction callback. Example:
  79796. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79797. *
  79798. * @param element html element to attach the vrDevice to
  79799. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79800. */
  79801. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79802. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79803. this._attached = true;
  79804. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79805. if (this._vrDevice) {
  79806. this.getEngine().enableVR();
  79807. }
  79808. };
  79809. /**
  79810. * Detaches the camera from the html element and disables VR
  79811. *
  79812. * @param element html element to detach from
  79813. */
  79814. WebVRFreeCamera.prototype.detachControl = function (element) {
  79815. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79816. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79817. _super.prototype.detachControl.call(this, element);
  79818. this._attached = false;
  79819. this.getEngine().disableVR();
  79820. };
  79821. /**
  79822. * @returns the name of this class
  79823. */
  79824. WebVRFreeCamera.prototype.getClassName = function () {
  79825. return "WebVRFreeCamera";
  79826. };
  79827. /**
  79828. * Calls resetPose on the vrDisplay
  79829. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79830. */
  79831. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79832. //uses the vrDisplay's "resetPose()".
  79833. //pitch and roll won't be affected.
  79834. this._vrDevice.resetPose();
  79835. };
  79836. /**
  79837. * Updates the rig cameras (left and right eye)
  79838. */
  79839. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79840. var camLeft = this._rigCameras[0];
  79841. var camRight = this._rigCameras[1];
  79842. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79843. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79844. camLeft.position.copyFrom(this._deviceRoomPosition);
  79845. camRight.position.copyFrom(this._deviceRoomPosition);
  79846. };
  79847. /**
  79848. * Updates the cached values of the camera
  79849. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79850. */
  79851. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79852. var _this = this;
  79853. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79854. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79855. if (!this.updateCacheCalled) {
  79856. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79857. this.updateCacheCalled = true;
  79858. this.update();
  79859. }
  79860. // Set working vector to the device position in room space rotated by the new rotation
  79861. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79862. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79863. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79864. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79865. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79866. // Add translation from anchor position
  79867. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79868. this._workingVector.addInPlace(this.position);
  79869. this._workingVector.subtractInPlace(this._cache.position);
  79870. this._deviceToWorld.setTranslation(this._workingVector);
  79871. // Set an inverted matrix to be used when updating the camera
  79872. this._deviceToWorld.invertToRef(this._worldToDevice);
  79873. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79874. this.controllers.forEach(function (controller) {
  79875. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  79876. controller.update();
  79877. });
  79878. }
  79879. if (!ignoreParentClass) {
  79880. _super.prototype._updateCache.call(this);
  79881. }
  79882. this.updateCacheCalled = false;
  79883. };
  79884. /**
  79885. * Updates the current device position and rotation in the babylon world
  79886. */
  79887. WebVRFreeCamera.prototype.update = function () {
  79888. // Get current device position in babylon world
  79889. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79890. // Get current device rotation in babylon world
  79891. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79892. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79893. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79894. _super.prototype.update.call(this);
  79895. };
  79896. /**
  79897. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79898. * @returns an identity matrix
  79899. */
  79900. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79901. return BABYLON.Matrix.Identity();
  79902. };
  79903. /**
  79904. * This function is called by the two RIG cameras.
  79905. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79906. */
  79907. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79908. var _this = this;
  79909. // Update the parent camera prior to using a child camera to avoid desynchronization
  79910. var parentCamera = this._cameraRigParams["parentCamera"];
  79911. parentCamera._updateCache();
  79912. //WebVR 1.1
  79913. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79914. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79915. if (!this.getScene().useRightHandedSystem) {
  79916. [2, 6, 8, 9, 14].forEach(function (num) {
  79917. _this._webvrViewMatrix.m[num] *= -1;
  79918. });
  79919. }
  79920. // update the camera rotation matrix
  79921. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79922. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79923. // Computing target and final matrix
  79924. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79925. // should the view matrix be updated with scale and position offset?
  79926. if (parentCamera.deviceScaleFactor !== 1) {
  79927. this._webvrViewMatrix.invert();
  79928. // scale the position, if set
  79929. if (parentCamera.deviceScaleFactor) {
  79930. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79931. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79932. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79933. }
  79934. this._webvrViewMatrix.invert();
  79935. }
  79936. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79937. return this._webvrViewMatrix;
  79938. };
  79939. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79940. var _this = this;
  79941. var parentCamera = this.parent;
  79942. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79943. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79944. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79945. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79946. //babylon compatible matrix
  79947. if (!this.getScene().useRightHandedSystem) {
  79948. [8, 9, 10, 11].forEach(function (num) {
  79949. _this._projectionMatrix.m[num] *= -1;
  79950. });
  79951. }
  79952. return this._projectionMatrix;
  79953. };
  79954. /**
  79955. * Initializes the controllers and their meshes
  79956. */
  79957. WebVRFreeCamera.prototype.initControllers = function () {
  79958. var _this = this;
  79959. this.controllers = [];
  79960. var manager = this.getScene().gamepadManager;
  79961. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79962. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79963. var webVrController = gamepad;
  79964. if (webVrController.defaultModel) {
  79965. webVrController.defaultModel.setEnabled(false);
  79966. }
  79967. if (webVrController.hand === "right") {
  79968. _this._rightController = null;
  79969. }
  79970. if (webVrController.hand === "left") {
  79971. _this._leftController = null;
  79972. }
  79973. var controllerIndex = _this.controllers.indexOf(webVrController);
  79974. if (controllerIndex !== -1) {
  79975. _this.controllers.splice(controllerIndex, 1);
  79976. }
  79977. }
  79978. });
  79979. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79980. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79981. var webVrController_1 = gamepad;
  79982. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  79983. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  79984. if (_this.webVROptions.controllerMeshes) {
  79985. if (webVrController_1.defaultModel) {
  79986. webVrController_1.defaultModel.setEnabled(true);
  79987. }
  79988. else {
  79989. // Load the meshes
  79990. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79991. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  79992. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79993. if (_this.webVROptions.defaultLightingOnControllers) {
  79994. if (!_this._lightOnControllers) {
  79995. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79996. }
  79997. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79998. var children = mesh.getChildren();
  79999. if (children.length !== 0) {
  80000. children.forEach(function (mesh) {
  80001. light.includedOnlyMeshes.push(mesh);
  80002. activateLightOnSubMeshes_1(mesh, light);
  80003. });
  80004. }
  80005. };
  80006. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80007. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80008. }
  80009. });
  80010. }
  80011. }
  80012. webVrController_1.attachToPoseControlledCamera(_this);
  80013. // since this is async - sanity check. Is the controller already stored?
  80014. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80015. //add to the controllers array
  80016. _this.controllers.push(webVrController_1);
  80017. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80018. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80019. // So we're overriding setting left & right manually to be sure
  80020. var firstViveWandDetected = false;
  80021. for (var i = 0; i < _this.controllers.length; i++) {
  80022. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80023. if (!firstViveWandDetected) {
  80024. firstViveWandDetected = true;
  80025. _this.controllers[i].hand = "left";
  80026. }
  80027. else {
  80028. _this.controllers[i].hand = "right";
  80029. }
  80030. }
  80031. }
  80032. //did we find enough controllers? Great! let the developer know.
  80033. if (_this.controllers.length >= 2) {
  80034. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80035. }
  80036. }
  80037. }
  80038. });
  80039. };
  80040. return WebVRFreeCamera;
  80041. }(BABYLON.FreeCamera));
  80042. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80043. })(BABYLON || (BABYLON = {}));
  80044. //# sourceMappingURL=babylon.webVRCamera.js.map
  80045. var BABYLON;
  80046. (function (BABYLON) {
  80047. // We're mainly based on the logic defined into the FreeCamera code
  80048. /**
  80049. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80050. * being tilted forward or back and left or right.
  80051. */
  80052. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80053. __extends(DeviceOrientationCamera, _super);
  80054. /**
  80055. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80056. * @param name The name of the camera
  80057. * @param position The start position camera
  80058. * @param scene The scene the camera belongs to
  80059. */
  80060. function DeviceOrientationCamera(name, position, scene) {
  80061. var _this = _super.call(this, name, position, scene) || this;
  80062. _this._quaternionCache = new BABYLON.Quaternion();
  80063. _this.inputs.addDeviceOrientation();
  80064. return _this;
  80065. }
  80066. /**
  80067. * Gets the current instance class name ("DeviceOrientationCamera").
  80068. * This helps avoiding instanceof at run time.
  80069. * @returns the class name
  80070. */
  80071. DeviceOrientationCamera.prototype.getClassName = function () {
  80072. return "DeviceOrientationCamera";
  80073. };
  80074. /**
  80075. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80076. */
  80077. DeviceOrientationCamera.prototype._checkInputs = function () {
  80078. _super.prototype._checkInputs.call(this);
  80079. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80080. if (this._initialQuaternion) {
  80081. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80082. }
  80083. };
  80084. /**
  80085. * Reset the camera to its default orientation on the specified axis only.
  80086. * @param axis The axis to reset
  80087. */
  80088. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80089. var _this = this;
  80090. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80091. //can only work if this camera has a rotation quaternion already.
  80092. if (!this.rotationQuaternion)
  80093. return;
  80094. if (!this._initialQuaternion) {
  80095. this._initialQuaternion = new BABYLON.Quaternion();
  80096. }
  80097. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80098. ['x', 'y', 'z'].forEach(function (axisName) {
  80099. if (!axis[axisName]) {
  80100. _this._initialQuaternion[axisName] = 0;
  80101. }
  80102. else {
  80103. _this._initialQuaternion[axisName] *= -1;
  80104. }
  80105. });
  80106. this._initialQuaternion.normalize();
  80107. //force rotation update
  80108. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80109. };
  80110. return DeviceOrientationCamera;
  80111. }(BABYLON.FreeCamera));
  80112. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80113. })(BABYLON || (BABYLON = {}));
  80114. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80115. var BABYLON;
  80116. (function (BABYLON) {
  80117. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80118. __extends(VRDeviceOrientationFreeCamera, _super);
  80119. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80120. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80121. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80122. var _this = _super.call(this, name, position, scene) || this;
  80123. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80124. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80125. return _this;
  80126. }
  80127. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80128. return "VRDeviceOrientationFreeCamera";
  80129. };
  80130. return VRDeviceOrientationFreeCamera;
  80131. }(BABYLON.DeviceOrientationCamera));
  80132. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80133. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80134. __extends(VRDeviceOrientationGamepadCamera, _super);
  80135. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80136. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80137. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80138. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80139. _this.inputs.addGamepad();
  80140. return _this;
  80141. }
  80142. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80143. return "VRDeviceOrientationGamepadCamera";
  80144. };
  80145. return VRDeviceOrientationGamepadCamera;
  80146. }(VRDeviceOrientationFreeCamera));
  80147. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80148. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80149. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80150. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80151. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80152. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80153. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80154. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80155. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80156. _this.inputs.addVRDeviceOrientation();
  80157. return _this;
  80158. }
  80159. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80160. return "VRDeviceOrientationArcRotateCamera";
  80161. };
  80162. return VRDeviceOrientationArcRotateCamera;
  80163. }(BABYLON.ArcRotateCamera));
  80164. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80165. })(BABYLON || (BABYLON = {}));
  80166. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80167. var BABYLON;
  80168. (function (BABYLON) {
  80169. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80170. __extends(AnaglyphFreeCamera, _super);
  80171. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80172. var _this = _super.call(this, name, position, scene) || this;
  80173. _this.interaxialDistance = interaxialDistance;
  80174. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80175. return _this;
  80176. }
  80177. AnaglyphFreeCamera.prototype.getClassName = function () {
  80178. return "AnaglyphFreeCamera";
  80179. };
  80180. return AnaglyphFreeCamera;
  80181. }(BABYLON.FreeCamera));
  80182. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80183. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80184. __extends(AnaglyphArcRotateCamera, _super);
  80185. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80186. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80187. _this.interaxialDistance = interaxialDistance;
  80188. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80189. return _this;
  80190. }
  80191. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80192. return "AnaglyphArcRotateCamera";
  80193. };
  80194. return AnaglyphArcRotateCamera;
  80195. }(BABYLON.ArcRotateCamera));
  80196. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80197. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80198. __extends(AnaglyphGamepadCamera, _super);
  80199. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80200. var _this = _super.call(this, name, position, scene) || this;
  80201. _this.interaxialDistance = interaxialDistance;
  80202. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80203. return _this;
  80204. }
  80205. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80206. return "AnaglyphGamepadCamera";
  80207. };
  80208. return AnaglyphGamepadCamera;
  80209. }(BABYLON.GamepadCamera));
  80210. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80211. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80212. __extends(AnaglyphUniversalCamera, _super);
  80213. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80214. var _this = _super.call(this, name, position, scene) || this;
  80215. _this.interaxialDistance = interaxialDistance;
  80216. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80217. return _this;
  80218. }
  80219. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80220. return "AnaglyphUniversalCamera";
  80221. };
  80222. return AnaglyphUniversalCamera;
  80223. }(BABYLON.UniversalCamera));
  80224. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80225. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80226. __extends(StereoscopicFreeCamera, _super);
  80227. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80228. var _this = _super.call(this, name, position, scene) || this;
  80229. _this.interaxialDistance = interaxialDistance;
  80230. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80231. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80232. return _this;
  80233. }
  80234. StereoscopicFreeCamera.prototype.getClassName = function () {
  80235. return "StereoscopicFreeCamera";
  80236. };
  80237. return StereoscopicFreeCamera;
  80238. }(BABYLON.FreeCamera));
  80239. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80240. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80241. __extends(StereoscopicArcRotateCamera, _super);
  80242. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80243. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80244. _this.interaxialDistance = interaxialDistance;
  80245. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80246. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80247. return _this;
  80248. }
  80249. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80250. return "StereoscopicArcRotateCamera";
  80251. };
  80252. return StereoscopicArcRotateCamera;
  80253. }(BABYLON.ArcRotateCamera));
  80254. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80255. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80256. __extends(StereoscopicGamepadCamera, _super);
  80257. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80258. var _this = _super.call(this, name, position, scene) || this;
  80259. _this.interaxialDistance = interaxialDistance;
  80260. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80261. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80262. return _this;
  80263. }
  80264. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80265. return "StereoscopicGamepadCamera";
  80266. };
  80267. return StereoscopicGamepadCamera;
  80268. }(BABYLON.GamepadCamera));
  80269. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80270. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80271. __extends(StereoscopicUniversalCamera, _super);
  80272. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80273. var _this = _super.call(this, name, position, scene) || this;
  80274. _this.interaxialDistance = interaxialDistance;
  80275. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80276. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80277. return _this;
  80278. }
  80279. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80280. return "StereoscopicUniversalCamera";
  80281. };
  80282. return StereoscopicUniversalCamera;
  80283. }(BABYLON.UniversalCamera));
  80284. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80285. })(BABYLON || (BABYLON = {}));
  80286. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80287. var BABYLON;
  80288. (function (BABYLON) {
  80289. var VRExperienceHelperGazer = /** @class */ (function () {
  80290. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80291. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80292. this.scene = scene;
  80293. this._pointerDownOnMeshAsked = false;
  80294. this._isActionableMesh = false;
  80295. this._teleportationRequestInitiated = false;
  80296. this._teleportationBackRequestInitiated = false;
  80297. this._dpadPressed = true;
  80298. this._activePointer = false;
  80299. this._id = VRExperienceHelperGazer._idCounter++;
  80300. // Gaze tracker
  80301. if (!gazeTrackerToClone) {
  80302. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80303. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80304. this._gazeTracker.isPickable = false;
  80305. this._gazeTracker.isVisible = false;
  80306. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80307. targetMat.specularColor = BABYLON.Color3.Black();
  80308. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80309. targetMat.backFaceCulling = false;
  80310. this._gazeTracker.material = targetMat;
  80311. }
  80312. else {
  80313. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80314. }
  80315. }
  80316. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80317. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80318. };
  80319. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80320. this._pointerDownOnMeshAsked = true;
  80321. if (this._currentMeshSelected && this._currentHit) {
  80322. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80323. }
  80324. };
  80325. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80326. if (this._currentMeshSelected && this._currentHit) {
  80327. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80328. }
  80329. this._pointerDownOnMeshAsked = false;
  80330. };
  80331. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80332. this._activePointer = true;
  80333. };
  80334. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80335. this._activePointer = false;
  80336. };
  80337. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80338. };
  80339. VRExperienceHelperGazer.prototype.dispose = function () {
  80340. this._interactionsEnabled = false;
  80341. this._teleportationEnabled = false;
  80342. };
  80343. VRExperienceHelperGazer._idCounter = 0;
  80344. return VRExperienceHelperGazer;
  80345. }());
  80346. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80347. __extends(VRExperienceHelperControllerGazer, _super);
  80348. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80349. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80350. _this.webVRController = webVRController;
  80351. // Laser pointer
  80352. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80353. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80354. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80355. laserPointerMaterial.alpha = 0.6;
  80356. _this._laserPointer.material = laserPointerMaterial;
  80357. _this._laserPointer.rotation.x = Math.PI / 2;
  80358. _this._laserPointer.position.z = -0.5;
  80359. _this._laserPointer.isVisible = false;
  80360. if (!webVRController.mesh) {
  80361. // Create an empty mesh that is used prior to loading the high quality model
  80362. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  80363. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  80364. preloadPointerPose.rotation.x = -0.7;
  80365. preloadMesh.addChild(preloadPointerPose);
  80366. webVRController.attachToMesh(preloadMesh);
  80367. }
  80368. _this._setLaserPointerParent(webVRController.mesh);
  80369. return _this;
  80370. }
  80371. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80372. return this.webVRController.getForwardRay(length);
  80373. };
  80374. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80375. _super.prototype._activatePointer.call(this);
  80376. this._laserPointer.isVisible = true;
  80377. };
  80378. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80379. _super.prototype._deactivatePointer.call(this);
  80380. this._laserPointer.isVisible = false;
  80381. };
  80382. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80383. this._laserPointer.material.emissiveColor = color;
  80384. };
  80385. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80386. var makeNotPick = function (root) {
  80387. root.name += " laserPointer";
  80388. root.getChildMeshes().forEach(function (c) {
  80389. makeNotPick(c);
  80390. });
  80391. };
  80392. makeNotPick(mesh);
  80393. var childMeshes = mesh.getChildMeshes();
  80394. for (var i = 0; i < childMeshes.length; i++) {
  80395. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  80396. mesh = childMeshes[i];
  80397. this.webVRController._pointingPoseNode = mesh;
  80398. break;
  80399. }
  80400. }
  80401. this._laserPointer.parent = mesh;
  80402. };
  80403. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80404. this._laserPointer.scaling.y = distance;
  80405. this._laserPointer.position.z = -distance / 2;
  80406. };
  80407. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80408. _super.prototype.dispose.call(this);
  80409. this._laserPointer.dispose();
  80410. };
  80411. return VRExperienceHelperControllerGazer;
  80412. }(VRExperienceHelperGazer));
  80413. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80414. __extends(VRExperienceHelperCameraGazer, _super);
  80415. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80416. var _this = _super.call(this, scene) || this;
  80417. _this.getCamera = getCamera;
  80418. return _this;
  80419. }
  80420. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80421. var camera = this.getCamera();
  80422. if (camera) {
  80423. return camera.getForwardRay(length);
  80424. }
  80425. else {
  80426. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80427. }
  80428. };
  80429. return VRExperienceHelperCameraGazer;
  80430. }(VRExperienceHelperGazer));
  80431. /**
  80432. * Helps to quickly add VR support to an existing scene.
  80433. * See http://doc.babylonjs.com/how_to/webvr_helper
  80434. */
  80435. var VRExperienceHelper = /** @class */ (function () {
  80436. /**
  80437. * Instantiates a VRExperienceHelper.
  80438. * Helps to quickly add VR support to an existing scene.
  80439. * @param scene The scene the VRExperienceHelper belongs to.
  80440. * @param webVROptions Options to modify the vr experience helper's behavior.
  80441. */
  80442. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80443. if (webVROptions === void 0) { webVROptions = {}; }
  80444. var _this = this;
  80445. this.webVROptions = webVROptions;
  80446. // Can the system support WebVR, even if a headset isn't plugged in?
  80447. this._webVRsupported = false;
  80448. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80449. this._webVRready = false;
  80450. // Are we waiting for the requestPresent callback to complete?
  80451. this._webVRrequesting = false;
  80452. // Are we presenting to the headset right now?
  80453. this._webVRpresenting = false;
  80454. // Are we presenting in the fullscreen fallback?
  80455. this._fullscreenVRpresenting = false;
  80456. /**
  80457. * Observable raised when entering VR.
  80458. */
  80459. this.onEnteringVRObservable = new BABYLON.Observable();
  80460. /**
  80461. * Observable raised when exiting VR.
  80462. */
  80463. this.onExitingVRObservable = new BABYLON.Observable();
  80464. /**
  80465. * Observable raised when controller mesh is loaded.
  80466. */
  80467. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80468. this._useCustomVRButton = false;
  80469. this._teleportationRequested = false;
  80470. this._teleportActive = false;
  80471. this._floorMeshesCollection = [];
  80472. this._rotationAllowed = true;
  80473. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80474. this._rotationRightAsked = false;
  80475. this._rotationLeftAsked = false;
  80476. this._isDefaultTeleportationTarget = true;
  80477. this._teleportationFillColor = "#444444";
  80478. this._teleportationBorderColor = "#FFFFFF";
  80479. this._rotationAngle = 0;
  80480. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80481. this._padSensibilityUp = 0.65;
  80482. this._padSensibilityDown = 0.35;
  80483. this.leftController = null;
  80484. this.rightController = null;
  80485. /**
  80486. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80487. */
  80488. this.onNewMeshSelected = new BABYLON.Observable();
  80489. /**
  80490. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80491. */
  80492. this.onNewMeshPicked = new BABYLON.Observable();
  80493. /**
  80494. * Observable raised before camera teleportation
  80495. */
  80496. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80497. /**
  80498. * Observable raised after camera teleportation
  80499. */
  80500. this.onAfterCameraTeleport = new BABYLON.Observable();
  80501. /**
  80502. * Observable raised when current selected mesh gets unselected
  80503. */
  80504. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80505. /**
  80506. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80507. */
  80508. this.teleportationEnabled = true;
  80509. this._teleportationInitialized = false;
  80510. this._interactionsEnabled = false;
  80511. this._interactionsRequested = false;
  80512. this._displayGaze = true;
  80513. this._displayLaserPointer = true;
  80514. this._onResize = function () {
  80515. _this.moveButtonToBottomRight();
  80516. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80517. _this.exitVR();
  80518. }
  80519. };
  80520. this._onFullscreenChange = function () {
  80521. if (document.fullscreen !== undefined) {
  80522. _this._fullscreenVRpresenting = document.fullscreen;
  80523. }
  80524. else if (document.mozFullScreen !== undefined) {
  80525. _this._fullscreenVRpresenting = document.mozFullScreen;
  80526. }
  80527. else if (document.webkitIsFullScreen !== undefined) {
  80528. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80529. }
  80530. else if (document.msIsFullScreen !== undefined) {
  80531. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80532. }
  80533. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80534. _this.exitVR();
  80535. if (!_this._useCustomVRButton) {
  80536. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80537. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80538. }
  80539. }
  80540. };
  80541. this.beforeRender = function () {
  80542. if (_this.leftController && _this.leftController._activePointer) {
  80543. _this._castRayAndSelectObject(_this.leftController);
  80544. }
  80545. if (_this.rightController && _this.rightController._activePointer) {
  80546. _this._castRayAndSelectObject(_this.rightController);
  80547. }
  80548. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80549. _this._castRayAndSelectObject(_this._cameraGazer);
  80550. }
  80551. else {
  80552. _this._cameraGazer._gazeTracker.isVisible = false;
  80553. }
  80554. };
  80555. this._onNewGamepadConnected = function (gamepad) {
  80556. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80557. if (gamepad.leftStick) {
  80558. gamepad.onleftstickchanged(function (stickValues) {
  80559. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80560. // Listening to classic/xbox gamepad only if no VR controller is active
  80561. if ((!_this.leftController && !_this.rightController) ||
  80562. ((_this.leftController && !_this.leftController._activePointer) &&
  80563. (_this.rightController && !_this.rightController._activePointer))) {
  80564. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80565. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80566. }
  80567. }
  80568. });
  80569. }
  80570. if (gamepad.rightStick) {
  80571. gamepad.onrightstickchanged(function (stickValues) {
  80572. if (_this._teleportationInitialized) {
  80573. _this._checkRotate(stickValues, _this._cameraGazer);
  80574. }
  80575. });
  80576. }
  80577. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80578. gamepad.onbuttondown(function (buttonPressed) {
  80579. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80580. _this._cameraGazer._selectionPointerDown();
  80581. }
  80582. });
  80583. gamepad.onbuttonup(function (buttonPressed) {
  80584. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80585. _this._cameraGazer._selectionPointerUp();
  80586. }
  80587. });
  80588. }
  80589. }
  80590. else {
  80591. var webVRController = gamepad;
  80592. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80593. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80594. _this.rightController = controller;
  80595. }
  80596. else {
  80597. _this.leftController = controller;
  80598. }
  80599. _this._tryEnableInteractionOnController(controller);
  80600. }
  80601. };
  80602. // 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
  80603. this._tryEnableInteractionOnController = function (controller) {
  80604. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80605. _this._enableInteractionOnController(controller);
  80606. }
  80607. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80608. _this._enableTeleportationOnController(controller);
  80609. }
  80610. };
  80611. this._onNewGamepadDisconnected = function (gamepad) {
  80612. if (gamepad instanceof BABYLON.WebVRController) {
  80613. if (gamepad.hand === "left" && _this.leftController != null) {
  80614. _this.leftController.dispose();
  80615. _this.leftController = null;
  80616. }
  80617. if (gamepad.hand === "right" && _this.rightController != null) {
  80618. _this.rightController.dispose();
  80619. _this.rightController = null;
  80620. }
  80621. }
  80622. };
  80623. this._workingVector = BABYLON.Vector3.Zero();
  80624. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80625. this._workingMatrix = BABYLON.Matrix.Identity();
  80626. this._scene = scene;
  80627. this._canvas = scene.getEngine().getRenderingCanvas();
  80628. // Parse options
  80629. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80630. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80631. }
  80632. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80633. webVROptions.createDeviceOrientationCamera = true;
  80634. }
  80635. if (webVROptions.defaultHeight === undefined) {
  80636. webVROptions.defaultHeight = 1.7;
  80637. }
  80638. if (webVROptions.useCustomVRButton) {
  80639. this._useCustomVRButton = true;
  80640. if (webVROptions.customVRButton) {
  80641. this._btnVR = webVROptions.customVRButton;
  80642. }
  80643. }
  80644. if (webVROptions.rayLength) {
  80645. this._rayLength = webVROptions.rayLength;
  80646. }
  80647. this._defaultHeight = webVROptions.defaultHeight;
  80648. if (webVROptions.positionScale) {
  80649. this._rayLength *= webVROptions.positionScale;
  80650. this._defaultHeight *= webVROptions.positionScale;
  80651. }
  80652. // Set position
  80653. if (this._scene.activeCamera) {
  80654. this._position = this._scene.activeCamera.position.clone();
  80655. }
  80656. else {
  80657. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80658. }
  80659. // Set non-vr camera
  80660. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80661. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80662. // Copy data from existing camera
  80663. if (this._scene.activeCamera) {
  80664. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80665. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80666. // Set rotation from previous camera
  80667. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80668. var targetCamera = this._scene.activeCamera;
  80669. if (targetCamera.rotationQuaternion) {
  80670. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80671. }
  80672. else {
  80673. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80674. }
  80675. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80676. }
  80677. }
  80678. this._scene.activeCamera = this._deviceOrientationCamera;
  80679. if (this._canvas) {
  80680. this._scene.activeCamera.attachControl(this._canvas);
  80681. }
  80682. }
  80683. else {
  80684. this._existingCamera = this._scene.activeCamera;
  80685. }
  80686. // Create VR cameras
  80687. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80688. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80689. }
  80690. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80691. this._webVRCamera.useStandingMatrix();
  80692. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80693. // Create default button
  80694. if (!this._useCustomVRButton) {
  80695. this._btnVR = document.createElement("BUTTON");
  80696. this._btnVR.className = "babylonVRicon";
  80697. this._btnVR.id = "babylonVRiconbtn";
  80698. this._btnVR.title = "Click to switch to VR";
  80699. 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) }";
  80700. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80701. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80702. // css += ".babylonVRicon.vrdisplaysupported { }";
  80703. // css += ".babylonVRicon.vrdisplayready { }";
  80704. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80705. var style = document.createElement('style');
  80706. style.appendChild(document.createTextNode(css));
  80707. document.getElementsByTagName('head')[0].appendChild(style);
  80708. this.moveButtonToBottomRight();
  80709. }
  80710. // VR button click event
  80711. if (this._btnVR) {
  80712. this._btnVR.addEventListener("click", function () {
  80713. if (!_this.isInVRMode) {
  80714. _this.enterVR();
  80715. }
  80716. else {
  80717. _this.exitVR();
  80718. }
  80719. });
  80720. }
  80721. // Window events
  80722. window.addEventListener("resize", this._onResize);
  80723. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80724. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80725. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80726. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80727. // Display vr button when headset is connected
  80728. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80729. this.displayVRButton();
  80730. }
  80731. else {
  80732. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80733. if (e.vrDisplay) {
  80734. _this.displayVRButton();
  80735. }
  80736. });
  80737. }
  80738. // Exiting VR mode using 'ESC' key on desktop
  80739. this._onKeyDown = function (event) {
  80740. if (event.keyCode === 27 && _this.isInVRMode) {
  80741. _this.exitVR();
  80742. }
  80743. };
  80744. document.addEventListener("keydown", this._onKeyDown);
  80745. // Exiting VR mode double tapping the touch screen
  80746. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80747. if (_this.isInVRMode) {
  80748. _this.exitVR();
  80749. if (_this._fullscreenVRpresenting) {
  80750. _this._scene.getEngine().switchFullscreen(true);
  80751. }
  80752. }
  80753. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80754. // Listen for WebVR display changes
  80755. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80756. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80757. this._onVRRequestPresentStart = function () {
  80758. _this._webVRrequesting = true;
  80759. _this.updateButtonVisibility();
  80760. };
  80761. this._onVRRequestPresentComplete = function (success) {
  80762. _this._webVRrequesting = false;
  80763. _this.updateButtonVisibility();
  80764. };
  80765. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80766. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80767. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80768. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80769. scene.onDisposeObservable.add(function () {
  80770. _this.dispose();
  80771. });
  80772. // Gamepad connection events
  80773. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80774. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80775. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80776. this.updateButtonVisibility();
  80777. //create easing functions
  80778. this._circleEase = new BABYLON.CircleEase();
  80779. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80780. }
  80781. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80782. /** Return this.onEnteringVRObservable
  80783. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80784. */
  80785. get: function () {
  80786. return this.onEnteringVRObservable;
  80787. },
  80788. enumerable: true,
  80789. configurable: true
  80790. });
  80791. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80792. /** Return this.onExitingVRObservable
  80793. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80794. */
  80795. get: function () {
  80796. return this.onExitingVRObservable;
  80797. },
  80798. enumerable: true,
  80799. configurable: true
  80800. });
  80801. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80802. /** Return this.onControllerMeshLoadedObservable
  80803. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80804. */
  80805. get: function () {
  80806. return this.onControllerMeshLoadedObservable;
  80807. },
  80808. enumerable: true,
  80809. configurable: true
  80810. });
  80811. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80812. /**
  80813. * The mesh used to display where the user is going to teleport.
  80814. */
  80815. get: function () {
  80816. return this._teleportationTarget;
  80817. },
  80818. /**
  80819. * Sets the mesh to be used to display where the user is going to teleport.
  80820. */
  80821. set: function (value) {
  80822. if (value) {
  80823. value.name = "teleportationTarget";
  80824. this._isDefaultTeleportationTarget = false;
  80825. this._teleportationTarget = value;
  80826. }
  80827. },
  80828. enumerable: true,
  80829. configurable: true
  80830. });
  80831. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80832. /**
  80833. * The mesh used to display where the user is selecting,
  80834. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80835. * See http://doc.babylonjs.com/resources/baking_transformations
  80836. */
  80837. get: function () {
  80838. return this._cameraGazer._gazeTracker;
  80839. },
  80840. set: function (value) {
  80841. if (value) {
  80842. this._cameraGazer._gazeTracker = value;
  80843. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80844. this._cameraGazer._gazeTracker.isPickable = false;
  80845. this._cameraGazer._gazeTracker.isVisible = false;
  80846. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80847. if (this.leftController) {
  80848. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80849. }
  80850. if (this.rightController) {
  80851. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80852. }
  80853. }
  80854. },
  80855. enumerable: true,
  80856. configurable: true
  80857. });
  80858. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80859. /**
  80860. * If the ray of the gaze should be displayed.
  80861. */
  80862. get: function () {
  80863. return this._displayGaze;
  80864. },
  80865. /**
  80866. * Sets if the ray of the gaze should be displayed.
  80867. */
  80868. set: function (value) {
  80869. this._displayGaze = value;
  80870. if (!value) {
  80871. this._cameraGazer._gazeTracker.isVisible = false;
  80872. if (this.leftController) {
  80873. this.leftController._gazeTracker.isVisible = false;
  80874. }
  80875. if (this.rightController) {
  80876. this.rightController._gazeTracker.isVisible = false;
  80877. }
  80878. }
  80879. },
  80880. enumerable: true,
  80881. configurable: true
  80882. });
  80883. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80884. /**
  80885. * If the ray of the LaserPointer should be displayed.
  80886. */
  80887. get: function () {
  80888. return this._displayLaserPointer;
  80889. },
  80890. /**
  80891. * Sets if the ray of the LaserPointer should be displayed.
  80892. */
  80893. set: function (value) {
  80894. this._displayLaserPointer = value;
  80895. if (!value) {
  80896. if (this.rightController) {
  80897. this.rightController._deactivatePointer();
  80898. this.rightController._gazeTracker.isVisible = false;
  80899. }
  80900. if (this.leftController) {
  80901. this.leftController._deactivatePointer();
  80902. this.leftController._gazeTracker.isVisible = false;
  80903. }
  80904. }
  80905. else {
  80906. if (this.rightController) {
  80907. this.rightController._activatePointer();
  80908. }
  80909. else if (this.leftController) {
  80910. this.leftController._activatePointer();
  80911. }
  80912. }
  80913. },
  80914. enumerable: true,
  80915. configurable: true
  80916. });
  80917. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80918. /**
  80919. * The deviceOrientationCamera used as the camera when not in VR.
  80920. */
  80921. get: function () {
  80922. return this._deviceOrientationCamera;
  80923. },
  80924. enumerable: true,
  80925. configurable: true
  80926. });
  80927. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80928. /**
  80929. * Based on the current WebVR support, returns the current VR camera used.
  80930. */
  80931. get: function () {
  80932. if (this._webVRready) {
  80933. return this._webVRCamera;
  80934. }
  80935. else {
  80936. return this._scene.activeCamera;
  80937. }
  80938. },
  80939. enumerable: true,
  80940. configurable: true
  80941. });
  80942. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80943. /**
  80944. * The webVRCamera which is used when in VR.
  80945. */
  80946. get: function () {
  80947. return this._webVRCamera;
  80948. },
  80949. enumerable: true,
  80950. configurable: true
  80951. });
  80952. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80953. /**
  80954. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80955. */
  80956. get: function () {
  80957. return this._vrDeviceOrientationCamera;
  80958. },
  80959. enumerable: true,
  80960. configurable: true
  80961. });
  80962. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  80963. get: function () {
  80964. var result = this._cameraGazer._teleportationRequestInitiated
  80965. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  80966. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  80967. return result;
  80968. },
  80969. enumerable: true,
  80970. configurable: true
  80971. });
  80972. // Raised when one of the controller has loaded successfully its associated default mesh
  80973. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80974. if (this.leftController && this.leftController.webVRController == webVRController) {
  80975. if (webVRController.mesh) {
  80976. this.leftController._setLaserPointerParent(webVRController.mesh);
  80977. }
  80978. }
  80979. if (this.rightController && this.rightController.webVRController == webVRController) {
  80980. if (webVRController.mesh) {
  80981. this.rightController._setLaserPointerParent(webVRController.mesh);
  80982. }
  80983. }
  80984. try {
  80985. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80986. }
  80987. catch (err) {
  80988. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80989. }
  80990. };
  80991. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80992. /**
  80993. * Gets a value indicating if we are currently in VR mode.
  80994. */
  80995. get: function () {
  80996. return this._webVRpresenting || this._fullscreenVRpresenting;
  80997. },
  80998. enumerable: true,
  80999. configurable: true
  81000. });
  81001. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81002. var vrDisplay = this._scene.getEngine().getVRDevice();
  81003. if (vrDisplay) {
  81004. var wasPresenting = this._webVRpresenting;
  81005. // A VR display is connected
  81006. this._webVRpresenting = vrDisplay.isPresenting;
  81007. if (wasPresenting && !this._webVRpresenting)
  81008. this.exitVR();
  81009. }
  81010. else {
  81011. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81012. }
  81013. this.updateButtonVisibility();
  81014. };
  81015. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81016. this._webVRsupported = eventArgs.vrSupported;
  81017. this._webVRready = !!eventArgs.vrDisplay;
  81018. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81019. this.updateButtonVisibility();
  81020. };
  81021. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81022. if (this._canvas && !this._useCustomVRButton) {
  81023. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81024. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81025. }
  81026. };
  81027. VRExperienceHelper.prototype.displayVRButton = function () {
  81028. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81029. document.body.appendChild(this._btnVR);
  81030. this._btnVRDisplayed = true;
  81031. }
  81032. };
  81033. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81034. if (!this._btnVR || this._useCustomVRButton) {
  81035. return;
  81036. }
  81037. this._btnVR.className = "babylonVRicon";
  81038. if (this.isInVRMode) {
  81039. this._btnVR.className += " vrdisplaypresenting";
  81040. }
  81041. else {
  81042. if (this._webVRready)
  81043. this._btnVR.className += " vrdisplayready";
  81044. if (this._webVRsupported)
  81045. this._btnVR.className += " vrdisplaysupported";
  81046. if (this._webVRrequesting)
  81047. this._btnVR.className += " vrdisplayrequesting";
  81048. }
  81049. };
  81050. /**
  81051. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81052. * Otherwise, will use the fullscreen API.
  81053. */
  81054. VRExperienceHelper.prototype.enterVR = function () {
  81055. if (this.onEnteringVRObservable) {
  81056. try {
  81057. this.onEnteringVRObservable.notifyObservers(this);
  81058. }
  81059. catch (err) {
  81060. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81061. }
  81062. }
  81063. if (this._scene.activeCamera) {
  81064. this._position = this._scene.activeCamera.position.clone();
  81065. // make sure that we return to the last active camera
  81066. this._existingCamera = this._scene.activeCamera;
  81067. }
  81068. if (this._webVRrequesting)
  81069. return;
  81070. // If WebVR is supported and a headset is connected
  81071. if (this._webVRready) {
  81072. if (!this._webVRpresenting) {
  81073. this._webVRCamera.position = this._position;
  81074. this._scene.activeCamera = this._webVRCamera;
  81075. }
  81076. }
  81077. else if (this._vrDeviceOrientationCamera) {
  81078. this._vrDeviceOrientationCamera.position = this._position;
  81079. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81080. this._scene.getEngine().switchFullscreen(true);
  81081. this.updateButtonVisibility();
  81082. }
  81083. if (this._scene.activeCamera && this._canvas) {
  81084. this._scene.activeCamera.attachControl(this._canvas);
  81085. }
  81086. if (this._interactionsEnabled) {
  81087. this._scene.registerBeforeRender(this.beforeRender);
  81088. }
  81089. };
  81090. /**
  81091. * Attempt to exit VR, or fullscreen.
  81092. */
  81093. VRExperienceHelper.prototype.exitVR = function () {
  81094. if (this.onExitingVRObservable) {
  81095. try {
  81096. this.onExitingVRObservable.notifyObservers(this);
  81097. }
  81098. catch (err) {
  81099. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81100. }
  81101. }
  81102. if (this._webVRpresenting) {
  81103. this._scene.getEngine().disableVR();
  81104. }
  81105. if (this._scene.activeCamera) {
  81106. this._position = this._scene.activeCamera.position.clone();
  81107. }
  81108. if (this._deviceOrientationCamera) {
  81109. this._deviceOrientationCamera.position = this._position;
  81110. this._scene.activeCamera = this._deviceOrientationCamera;
  81111. if (this._canvas) {
  81112. this._scene.activeCamera.attachControl(this._canvas);
  81113. }
  81114. }
  81115. else if (this._existingCamera) {
  81116. this._existingCamera.position = this._position;
  81117. this._scene.activeCamera = this._existingCamera;
  81118. }
  81119. this.updateButtonVisibility();
  81120. if (this._interactionsEnabled) {
  81121. this._scene.unregisterBeforeRender(this.beforeRender);
  81122. }
  81123. };
  81124. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81125. /**
  81126. * The position of the vr experience helper.
  81127. */
  81128. get: function () {
  81129. return this._position;
  81130. },
  81131. /**
  81132. * Sets the position of the vr experience helper.
  81133. */
  81134. set: function (value) {
  81135. this._position = value;
  81136. if (this._scene.activeCamera) {
  81137. this._scene.activeCamera.position = value;
  81138. }
  81139. },
  81140. enumerable: true,
  81141. configurable: true
  81142. });
  81143. /**
  81144. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81145. */
  81146. VRExperienceHelper.prototype.enableInteractions = function () {
  81147. var _this = this;
  81148. if (!this._interactionsEnabled) {
  81149. this._interactionsRequested = true;
  81150. if (this.leftController) {
  81151. this._enableInteractionOnController(this.leftController);
  81152. }
  81153. if (this.rightController) {
  81154. this._enableInteractionOnController(this.rightController);
  81155. }
  81156. this.raySelectionPredicate = function (mesh) {
  81157. return mesh.isVisible;
  81158. };
  81159. this.meshSelectionPredicate = function (mesh) {
  81160. return true;
  81161. };
  81162. this._raySelectionPredicate = function (mesh) {
  81163. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81164. && mesh.name.indexOf("teleportationTarget") === -1
  81165. && mesh.name.indexOf("torusTeleportation") === -1
  81166. && mesh.name.indexOf("laserPointer") === -1)) {
  81167. return _this.raySelectionPredicate(mesh);
  81168. }
  81169. return false;
  81170. };
  81171. this._interactionsEnabled = true;
  81172. }
  81173. };
  81174. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81175. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81176. if (this._floorMeshesCollection[i].id === mesh.id) {
  81177. return true;
  81178. }
  81179. }
  81180. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81181. return true;
  81182. }
  81183. return false;
  81184. };
  81185. /**
  81186. * Adds a floor mesh to be used for teleportation.
  81187. * @param floorMesh the mesh to be used for teleportation.
  81188. */
  81189. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81190. if (!this._floorMeshesCollection) {
  81191. return;
  81192. }
  81193. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81194. return;
  81195. }
  81196. this._floorMeshesCollection.push(floorMesh);
  81197. };
  81198. /**
  81199. * Removes a floor mesh from being used for teleportation.
  81200. * @param floorMesh the mesh to be removed.
  81201. */
  81202. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81203. if (!this._floorMeshesCollection) {
  81204. return;
  81205. }
  81206. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81207. if (meshIndex !== -1) {
  81208. this._floorMeshesCollection.splice(meshIndex, 1);
  81209. }
  81210. };
  81211. /**
  81212. * Enables interactions and teleportation using the VR controllers and gaze.
  81213. * @param vrTeleportationOptions options to modify teleportation behavior.
  81214. */
  81215. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81216. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81217. if (!this._teleportationInitialized) {
  81218. this._teleportationRequested = true;
  81219. this.enableInteractions();
  81220. if (vrTeleportationOptions.floorMeshName) {
  81221. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81222. }
  81223. if (vrTeleportationOptions.floorMeshes) {
  81224. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81225. }
  81226. if (this.leftController != null) {
  81227. this._enableTeleportationOnController(this.leftController);
  81228. }
  81229. if (this.rightController != null) {
  81230. this._enableTeleportationOnController(this.rightController);
  81231. }
  81232. // Creates an image processing post process for the vignette not relying
  81233. // on the main scene configuration for image processing to reduce setup and spaces
  81234. // (gamma/linear) conflicts.
  81235. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81236. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81237. imageProcessingConfiguration.vignetteEnabled = true;
  81238. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81239. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81240. this._teleportationInitialized = true;
  81241. if (this._isDefaultTeleportationTarget) {
  81242. this._createTeleportationCircles();
  81243. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81244. }
  81245. }
  81246. };
  81247. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81248. var _this = this;
  81249. var controllerMesh = controller.webVRController.mesh;
  81250. if (controllerMesh) {
  81251. controller._interactionsEnabled = true;
  81252. controller._activatePointer();
  81253. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81254. // Enabling / disabling laserPointer
  81255. if (_this._displayLaserPointer && stateObject.value === 1) {
  81256. if (controller._activePointer) {
  81257. controller._deactivatePointer();
  81258. }
  81259. else {
  81260. controller._activatePointer();
  81261. }
  81262. if (_this.displayGaze) {
  81263. controller._gazeTracker.isVisible = controller._activePointer;
  81264. }
  81265. }
  81266. });
  81267. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81268. if (!controller._pointerDownOnMeshAsked) {
  81269. if (stateObject.value > _this._padSensibilityUp) {
  81270. controller._selectionPointerDown();
  81271. }
  81272. }
  81273. else if (stateObject.value < _this._padSensibilityDown) {
  81274. controller._selectionPointerUp();
  81275. }
  81276. });
  81277. }
  81278. };
  81279. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81280. // Dont teleport if another gaze already requested teleportation
  81281. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81282. return;
  81283. }
  81284. if (!gazer._teleportationRequestInitiated) {
  81285. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81286. gazer._activatePointer();
  81287. gazer._teleportationRequestInitiated = true;
  81288. }
  81289. }
  81290. else {
  81291. // Listening to the proper controller values changes to confirm teleportation
  81292. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81293. if (this._teleportActive) {
  81294. this._teleportCamera(this._haloCenter);
  81295. }
  81296. gazer._teleportationRequestInitiated = false;
  81297. }
  81298. }
  81299. };
  81300. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81301. // Only rotate when user is not currently selecting a teleportation location
  81302. if (gazer._teleportationRequestInitiated) {
  81303. return;
  81304. }
  81305. if (!this._rotationLeftAsked) {
  81306. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81307. this._rotationLeftAsked = true;
  81308. if (this._rotationAllowed) {
  81309. this._rotateCamera(false);
  81310. }
  81311. }
  81312. }
  81313. else {
  81314. if (stateObject.x > -this._padSensibilityDown) {
  81315. this._rotationLeftAsked = false;
  81316. }
  81317. }
  81318. if (!this._rotationRightAsked) {
  81319. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81320. this._rotationRightAsked = true;
  81321. if (this._rotationAllowed) {
  81322. this._rotateCamera(true);
  81323. }
  81324. }
  81325. }
  81326. else {
  81327. if (stateObject.x < this._padSensibilityDown) {
  81328. this._rotationRightAsked = false;
  81329. }
  81330. }
  81331. };
  81332. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81333. // Only teleport backwards when user is not currently selecting a teleportation location
  81334. if (gazer._teleportationRequestInitiated) {
  81335. return;
  81336. }
  81337. // Teleport backwards
  81338. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81339. if (!gazer._teleportationBackRequestInitiated) {
  81340. if (!this.currentVRCamera) {
  81341. return;
  81342. }
  81343. // Get rotation and position of the current camera
  81344. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81345. var position = this.currentVRCamera.position;
  81346. // If the camera has device position, use that instead
  81347. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81348. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81349. position = this.currentVRCamera.devicePosition;
  81350. }
  81351. // Get matrix with only the y rotation of the device rotation
  81352. rotation.toEulerAnglesToRef(this._workingVector);
  81353. this._workingVector.z = 0;
  81354. this._workingVector.x = 0;
  81355. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81356. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81357. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81358. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81359. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81360. var ray = new BABYLON.Ray(position, this._workingVector);
  81361. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81362. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81363. this._teleportCamera(hit.pickedPoint);
  81364. }
  81365. gazer._teleportationBackRequestInitiated = true;
  81366. }
  81367. }
  81368. else {
  81369. gazer._teleportationBackRequestInitiated = false;
  81370. }
  81371. };
  81372. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81373. var _this = this;
  81374. var controllerMesh = controller.webVRController.mesh;
  81375. if (controllerMesh) {
  81376. if (!controller._interactionsEnabled) {
  81377. this._enableInteractionOnController(controller);
  81378. }
  81379. controller._interactionsEnabled = true;
  81380. controller._teleportationEnabled = true;
  81381. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81382. controller._dpadPressed = false;
  81383. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81384. controller._dpadPressed = stateObject.pressed;
  81385. if (!controller._dpadPressed) {
  81386. _this._rotationLeftAsked = false;
  81387. _this._rotationRightAsked = false;
  81388. controller._teleportationBackRequestInitiated = false;
  81389. }
  81390. });
  81391. }
  81392. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81393. if (_this.teleportationEnabled) {
  81394. _this._checkTeleportBackwards(stateObject, controller);
  81395. _this._checkTeleportWithRay(stateObject, controller);
  81396. }
  81397. _this._checkRotate(stateObject, controller);
  81398. });
  81399. }
  81400. };
  81401. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81402. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81403. this._teleportationTarget.isPickable = false;
  81404. var length = 512;
  81405. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81406. dynamicTexture.hasAlpha = true;
  81407. var context = dynamicTexture.getContext();
  81408. var centerX = length / 2;
  81409. var centerY = length / 2;
  81410. var radius = 200;
  81411. context.beginPath();
  81412. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81413. context.fillStyle = this._teleportationFillColor;
  81414. context.fill();
  81415. context.lineWidth = 10;
  81416. context.strokeStyle = this._teleportationBorderColor;
  81417. context.stroke();
  81418. context.closePath();
  81419. dynamicTexture.update();
  81420. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81421. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81422. this._teleportationTarget.material = teleportationCircleMaterial;
  81423. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81424. torus.isPickable = false;
  81425. torus.parent = this._teleportationTarget;
  81426. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81427. var keys = [];
  81428. keys.push({
  81429. frame: 0,
  81430. value: 0
  81431. });
  81432. keys.push({
  81433. frame: 30,
  81434. value: 0.4
  81435. });
  81436. keys.push({
  81437. frame: 60,
  81438. value: 0
  81439. });
  81440. animationInnerCircle.setKeys(keys);
  81441. var easingFunction = new BABYLON.SineEase();
  81442. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81443. animationInnerCircle.setEasingFunction(easingFunction);
  81444. torus.animations = [];
  81445. torus.animations.push(animationInnerCircle);
  81446. this._scene.beginAnimation(torus, 0, 60, true);
  81447. this._hideTeleportationTarget();
  81448. };
  81449. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81450. this._teleportActive = true;
  81451. if (this._teleportationInitialized) {
  81452. this._teleportationTarget.isVisible = true;
  81453. if (this._isDefaultTeleportationTarget) {
  81454. this._teleportationTarget.getChildren()[0].isVisible = true;
  81455. }
  81456. }
  81457. };
  81458. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81459. this._teleportActive = false;
  81460. if (this._teleportationInitialized) {
  81461. this._teleportationTarget.isVisible = false;
  81462. if (this._isDefaultTeleportationTarget) {
  81463. this._teleportationTarget.getChildren()[0].isVisible = false;
  81464. }
  81465. }
  81466. };
  81467. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81468. var _this = this;
  81469. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81470. return;
  81471. }
  81472. if (right) {
  81473. this._rotationAngle++;
  81474. }
  81475. else {
  81476. this._rotationAngle--;
  81477. }
  81478. this.currentVRCamera.animations = [];
  81479. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81480. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81481. var animationRotationKeys = [];
  81482. animationRotationKeys.push({
  81483. frame: 0,
  81484. value: this.currentVRCamera.rotationQuaternion
  81485. });
  81486. animationRotationKeys.push({
  81487. frame: 6,
  81488. value: target
  81489. });
  81490. animationRotation.setKeys(animationRotationKeys);
  81491. animationRotation.setEasingFunction(this._circleEase);
  81492. this.currentVRCamera.animations.push(animationRotation);
  81493. this._postProcessMove.animations = [];
  81494. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81495. var vignetteWeightKeys = [];
  81496. vignetteWeightKeys.push({
  81497. frame: 0,
  81498. value: 0
  81499. });
  81500. vignetteWeightKeys.push({
  81501. frame: 3,
  81502. value: 4
  81503. });
  81504. vignetteWeightKeys.push({
  81505. frame: 6,
  81506. value: 0
  81507. });
  81508. animationPP.setKeys(vignetteWeightKeys);
  81509. animationPP.setEasingFunction(this._circleEase);
  81510. this._postProcessMove.animations.push(animationPP);
  81511. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81512. var vignetteStretchKeys = [];
  81513. vignetteStretchKeys.push({
  81514. frame: 0,
  81515. value: 0
  81516. });
  81517. vignetteStretchKeys.push({
  81518. frame: 3,
  81519. value: 10
  81520. });
  81521. vignetteStretchKeys.push({
  81522. frame: 6,
  81523. value: 0
  81524. });
  81525. animationPP2.setKeys(vignetteStretchKeys);
  81526. animationPP2.setEasingFunction(this._circleEase);
  81527. this._postProcessMove.animations.push(animationPP2);
  81528. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81529. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81530. this._postProcessMove.samples = 4;
  81531. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81532. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81533. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81534. });
  81535. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81536. };
  81537. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81538. if (hit.pickedPoint) {
  81539. if (gazer._teleportationRequestInitiated) {
  81540. this._displayTeleportationTarget();
  81541. this._haloCenter.copyFrom(hit.pickedPoint);
  81542. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81543. }
  81544. var pickNormal = hit.getNormal(true, false);
  81545. if (pickNormal) {
  81546. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81547. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81548. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81549. }
  81550. this._teleportationTarget.position.y += 0.1;
  81551. }
  81552. };
  81553. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81554. var _this = this;
  81555. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81556. return;
  81557. }
  81558. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81559. // offset of the headset from the anchor.
  81560. if (this.webVRCamera.leftCamera) {
  81561. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81562. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81563. location.subtractToRef(this._workingVector, this._workingVector);
  81564. }
  81565. else {
  81566. this._workingVector.copyFrom(location);
  81567. }
  81568. // Add height to account for user's height offset
  81569. if (this.isInVRMode) {
  81570. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  81571. }
  81572. else {
  81573. this._workingVector.y += this._defaultHeight;
  81574. }
  81575. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81576. // Create animation from the camera's position to the new location
  81577. this.currentVRCamera.animations = [];
  81578. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81579. var animationCameraTeleportationKeys = [{
  81580. frame: 0,
  81581. value: this.currentVRCamera.position
  81582. },
  81583. {
  81584. frame: 11,
  81585. value: this._workingVector
  81586. }
  81587. ];
  81588. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81589. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81590. this.currentVRCamera.animations.push(animationCameraTeleportation);
  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: 5,
  81600. value: 8
  81601. });
  81602. vignetteWeightKeys.push({
  81603. frame: 11,
  81604. value: 0
  81605. });
  81606. animationPP.setKeys(vignetteWeightKeys);
  81607. this._postProcessMove.animations.push(animationPP);
  81608. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81609. var vignetteStretchKeys = [];
  81610. vignetteStretchKeys.push({
  81611. frame: 0,
  81612. value: 0
  81613. });
  81614. vignetteStretchKeys.push({
  81615. frame: 5,
  81616. value: 10
  81617. });
  81618. vignetteStretchKeys.push({
  81619. frame: 11,
  81620. value: 0
  81621. });
  81622. animationPP2.setKeys(vignetteStretchKeys);
  81623. this._postProcessMove.animations.push(animationPP2);
  81624. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81625. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81626. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81627. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81628. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81629. });
  81630. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81631. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81632. });
  81633. this._hideTeleportationTarget();
  81634. };
  81635. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81636. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81637. return;
  81638. }
  81639. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81640. // Moving the gazeTracker on the mesh face targetted
  81641. if (hit && hit.pickedPoint) {
  81642. if (this._displayGaze) {
  81643. var multiplier = 1;
  81644. gazer._gazeTracker.isVisible = true;
  81645. if (gazer._isActionableMesh) {
  81646. multiplier = 3;
  81647. }
  81648. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81649. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81650. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81651. var pickNormal = hit.getNormal();
  81652. // To avoid z-fighting
  81653. var deltaFighting = 0.002;
  81654. if (pickNormal) {
  81655. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81656. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81657. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81658. }
  81659. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81660. if (gazer._gazeTracker.position.x < 0) {
  81661. gazer._gazeTracker.position.x += deltaFighting;
  81662. }
  81663. else {
  81664. gazer._gazeTracker.position.x -= deltaFighting;
  81665. }
  81666. if (gazer._gazeTracker.position.y < 0) {
  81667. gazer._gazeTracker.position.y += deltaFighting;
  81668. }
  81669. else {
  81670. gazer._gazeTracker.position.y -= deltaFighting;
  81671. }
  81672. if (gazer._gazeTracker.position.z < 0) {
  81673. gazer._gazeTracker.position.z += deltaFighting;
  81674. }
  81675. else {
  81676. gazer._gazeTracker.position.z -= deltaFighting;
  81677. }
  81678. }
  81679. // Changing the size of the laser pointer based on the distance from the targetted point
  81680. gazer._updatePointerDistance(hit.distance);
  81681. }
  81682. else {
  81683. gazer._gazeTracker.isVisible = false;
  81684. }
  81685. if (hit && hit.pickedMesh) {
  81686. gazer._currentHit = hit;
  81687. if (gazer._pointerDownOnMeshAsked) {
  81688. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81689. }
  81690. // The object selected is the floor, we're in a teleportation scenario
  81691. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81692. // Moving the teleportation area to this targetted point
  81693. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81694. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81695. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81696. }
  81697. gazer._currentMeshSelected = null;
  81698. if (gazer._teleportationRequestInitiated) {
  81699. this._moveTeleportationSelectorTo(hit, gazer);
  81700. }
  81701. return;
  81702. }
  81703. // If not, we're in a selection scenario
  81704. //this._teleportationAllowed = false;
  81705. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81706. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81707. this.onNewMeshPicked.notifyObservers(hit);
  81708. gazer._currentMeshSelected = hit.pickedMesh;
  81709. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81710. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81711. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81712. gazer._isActionableMesh = true;
  81713. }
  81714. else {
  81715. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81716. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81717. gazer._isActionableMesh = false;
  81718. }
  81719. try {
  81720. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81721. }
  81722. catch (err) {
  81723. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81724. }
  81725. }
  81726. else {
  81727. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81728. gazer._currentMeshSelected = null;
  81729. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81730. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81731. }
  81732. }
  81733. }
  81734. else {
  81735. gazer._currentHit = null;
  81736. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81737. gazer._currentMeshSelected = null;
  81738. //this._teleportationAllowed = false;
  81739. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81740. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81741. }
  81742. };
  81743. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81744. if (mesh) {
  81745. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81746. }
  81747. };
  81748. /**
  81749. * Sets the color of the laser ray from the vr controllers.
  81750. * @param color new color for the ray.
  81751. */
  81752. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81753. if (this.leftController) {
  81754. this.leftController._setLaserPointerColor(color);
  81755. }
  81756. if (this.rightController) {
  81757. this.rightController._setLaserPointerColor(color);
  81758. }
  81759. };
  81760. /**
  81761. * Sets the color of the ray from the vr headsets gaze.
  81762. * @param color new color for the ray.
  81763. */
  81764. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81765. if (!this._cameraGazer._gazeTracker.material) {
  81766. return;
  81767. }
  81768. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81769. if (this.leftController) {
  81770. this.leftController._gazeTracker.material.emissiveColor = color;
  81771. }
  81772. if (this.rightController) {
  81773. this.rightController._gazeTracker.material.emissiveColor = color;
  81774. }
  81775. };
  81776. /**
  81777. * Exits VR and disposes of the vr experience helper
  81778. */
  81779. VRExperienceHelper.prototype.dispose = function () {
  81780. if (this.isInVRMode) {
  81781. this.exitVR();
  81782. }
  81783. if (this._postProcessMove) {
  81784. this._postProcessMove.dispose();
  81785. }
  81786. if (this._webVRCamera) {
  81787. this._webVRCamera.dispose();
  81788. }
  81789. if (this._vrDeviceOrientationCamera) {
  81790. this._vrDeviceOrientationCamera.dispose();
  81791. }
  81792. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81793. document.body.removeChild(this._btnVR);
  81794. }
  81795. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81796. this._deviceOrientationCamera.dispose();
  81797. }
  81798. if (this._cameraGazer) {
  81799. this._cameraGazer.dispose();
  81800. }
  81801. if (this.leftController) {
  81802. this.leftController.dispose();
  81803. }
  81804. if (this.rightController) {
  81805. this.rightController.dispose();
  81806. }
  81807. if (this._teleportationTarget) {
  81808. this._teleportationTarget.dispose();
  81809. }
  81810. this._floorMeshesCollection = [];
  81811. document.removeEventListener("keydown", this._onKeyDown);
  81812. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81813. window.removeEventListener("resize", this._onResize);
  81814. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81815. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81816. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81817. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81818. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81819. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81820. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81821. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81822. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81823. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81824. this._scene.unregisterBeforeRender(this.beforeRender);
  81825. };
  81826. /**
  81827. * Gets the name of the VRExperienceHelper class
  81828. * @returns "VRExperienceHelper"
  81829. */
  81830. VRExperienceHelper.prototype.getClassName = function () {
  81831. return "VRExperienceHelper";
  81832. };
  81833. return VRExperienceHelper;
  81834. }());
  81835. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81836. })(BABYLON || (BABYLON = {}));
  81837. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81838. // Mainly based on these 2 articles :
  81839. // 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
  81840. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81841. var BABYLON;
  81842. (function (BABYLON) {
  81843. var JoystickAxis;
  81844. (function (JoystickAxis) {
  81845. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81846. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81847. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81848. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81849. var VirtualJoystick = /** @class */ (function () {
  81850. function VirtualJoystick(leftJoystick) {
  81851. var _this = this;
  81852. if (leftJoystick) {
  81853. this._leftJoystick = true;
  81854. }
  81855. else {
  81856. this._leftJoystick = false;
  81857. }
  81858. VirtualJoystick._globalJoystickIndex++;
  81859. // By default left & right arrow keys are moving the X
  81860. // and up & down keys are moving the Y
  81861. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81862. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81863. this.reverseLeftRight = false;
  81864. this.reverseUpDown = false;
  81865. // collections of pointers
  81866. this._touches = new BABYLON.StringDictionary();
  81867. this.deltaPosition = BABYLON.Vector3.Zero();
  81868. this._joystickSensibility = 25;
  81869. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81870. this._onResize = function (evt) {
  81871. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81872. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81873. if (VirtualJoystick.vjCanvas) {
  81874. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81875. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81876. }
  81877. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81878. };
  81879. // injecting a canvas element on top of the canvas 3D game
  81880. if (!VirtualJoystick.vjCanvas) {
  81881. window.addEventListener("resize", this._onResize, false);
  81882. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81883. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81884. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81885. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81886. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81887. VirtualJoystick.vjCanvas.style.width = "100%";
  81888. VirtualJoystick.vjCanvas.style.height = "100%";
  81889. VirtualJoystick.vjCanvas.style.position = "absolute";
  81890. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81891. VirtualJoystick.vjCanvas.style.top = "0px";
  81892. VirtualJoystick.vjCanvas.style.left = "0px";
  81893. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81894. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81895. // Support for jQuery PEP polyfill
  81896. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81897. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81898. if (!context) {
  81899. throw new Error("Unable to create canvas for virtual joystick");
  81900. }
  81901. VirtualJoystick.vjCanvasContext = context;
  81902. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81903. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81904. document.body.appendChild(VirtualJoystick.vjCanvas);
  81905. }
  81906. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81907. this.pressed = false;
  81908. // default joystick color
  81909. this._joystickColor = "cyan";
  81910. this._joystickPointerID = -1;
  81911. // current joystick position
  81912. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81913. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81914. // origin joystick position
  81915. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81916. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81917. this._onPointerDownHandlerRef = function (evt) {
  81918. _this._onPointerDown(evt);
  81919. };
  81920. this._onPointerMoveHandlerRef = function (evt) {
  81921. _this._onPointerMove(evt);
  81922. };
  81923. this._onPointerUpHandlerRef = function (evt) {
  81924. _this._onPointerUp(evt);
  81925. };
  81926. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81927. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81928. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81929. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81930. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81931. evt.preventDefault(); // Disables system menu
  81932. }, false);
  81933. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81934. }
  81935. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81936. this._joystickSensibility = newJoystickSensibility;
  81937. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81938. };
  81939. VirtualJoystick.prototype._onPointerDown = function (e) {
  81940. var positionOnScreenCondition;
  81941. e.preventDefault();
  81942. if (this._leftJoystick === true) {
  81943. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81944. }
  81945. else {
  81946. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81947. }
  81948. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81949. // First contact will be dedicated to the virtual joystick
  81950. this._joystickPointerID = e.pointerId;
  81951. this._joystickPointerStartPos.x = e.clientX;
  81952. this._joystickPointerStartPos.y = e.clientY;
  81953. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81954. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81955. this._deltaJoystickVector.x = 0;
  81956. this._deltaJoystickVector.y = 0;
  81957. this.pressed = true;
  81958. this._touches.add(e.pointerId.toString(), e);
  81959. }
  81960. else {
  81961. // You can only trigger the action buttons with a joystick declared
  81962. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81963. this._action();
  81964. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81965. }
  81966. }
  81967. };
  81968. VirtualJoystick.prototype._onPointerMove = function (e) {
  81969. // If the current pointer is the one associated to the joystick (first touch contact)
  81970. if (this._joystickPointerID == e.pointerId) {
  81971. this._joystickPointerPos.x = e.clientX;
  81972. this._joystickPointerPos.y = e.clientY;
  81973. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81974. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81975. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81976. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81977. switch (this._axisTargetedByLeftAndRight) {
  81978. case JoystickAxis.X:
  81979. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81980. break;
  81981. case JoystickAxis.Y:
  81982. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81983. break;
  81984. case JoystickAxis.Z:
  81985. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81986. break;
  81987. }
  81988. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81989. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81990. switch (this._axisTargetedByUpAndDown) {
  81991. case JoystickAxis.X:
  81992. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81993. break;
  81994. case JoystickAxis.Y:
  81995. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81996. break;
  81997. case JoystickAxis.Z:
  81998. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81999. break;
  82000. }
  82001. }
  82002. else {
  82003. var data = this._touches.get(e.pointerId.toString());
  82004. if (data) {
  82005. data.x = e.clientX;
  82006. data.y = e.clientY;
  82007. }
  82008. }
  82009. };
  82010. VirtualJoystick.prototype._onPointerUp = function (e) {
  82011. if (this._joystickPointerID == e.pointerId) {
  82012. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82013. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82014. this._joystickPointerID = -1;
  82015. this.pressed = false;
  82016. }
  82017. else {
  82018. var touch = this._touches.get(e.pointerId.toString());
  82019. if (touch) {
  82020. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82021. }
  82022. }
  82023. this._deltaJoystickVector.x = 0;
  82024. this._deltaJoystickVector.y = 0;
  82025. this._touches.remove(e.pointerId.toString());
  82026. };
  82027. /**
  82028. * Change the color of the virtual joystick
  82029. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82030. */
  82031. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82032. this._joystickColor = newColor;
  82033. };
  82034. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82035. this._action = action;
  82036. };
  82037. // Define which axis you'd like to control for left & right
  82038. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82039. switch (axis) {
  82040. case JoystickAxis.X:
  82041. case JoystickAxis.Y:
  82042. case JoystickAxis.Z:
  82043. this._axisTargetedByLeftAndRight = axis;
  82044. break;
  82045. default:
  82046. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82047. break;
  82048. }
  82049. };
  82050. // Define which axis you'd like to control for up & down
  82051. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82052. switch (axis) {
  82053. case JoystickAxis.X:
  82054. case JoystickAxis.Y:
  82055. case JoystickAxis.Z:
  82056. this._axisTargetedByUpAndDown = axis;
  82057. break;
  82058. default:
  82059. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82060. break;
  82061. }
  82062. };
  82063. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82064. var _this = this;
  82065. if (this.pressed) {
  82066. this._touches.forEach(function (key, touch) {
  82067. if (touch.pointerId === _this._joystickPointerID) {
  82068. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82069. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82070. VirtualJoystick.vjCanvasContext.beginPath();
  82071. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82072. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82073. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82074. VirtualJoystick.vjCanvasContext.stroke();
  82075. VirtualJoystick.vjCanvasContext.closePath();
  82076. VirtualJoystick.vjCanvasContext.beginPath();
  82077. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82078. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82079. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82080. VirtualJoystick.vjCanvasContext.stroke();
  82081. VirtualJoystick.vjCanvasContext.closePath();
  82082. VirtualJoystick.vjCanvasContext.beginPath();
  82083. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82084. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82085. VirtualJoystick.vjCanvasContext.stroke();
  82086. VirtualJoystick.vjCanvasContext.closePath();
  82087. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82088. }
  82089. else {
  82090. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82091. VirtualJoystick.vjCanvasContext.beginPath();
  82092. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82093. VirtualJoystick.vjCanvasContext.beginPath();
  82094. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82095. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82096. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82097. VirtualJoystick.vjCanvasContext.stroke();
  82098. VirtualJoystick.vjCanvasContext.closePath();
  82099. touch.prevX = touch.x;
  82100. touch.prevY = touch.y;
  82101. }
  82102. ;
  82103. });
  82104. }
  82105. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82106. };
  82107. VirtualJoystick.prototype.releaseCanvas = function () {
  82108. if (VirtualJoystick.vjCanvas) {
  82109. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82110. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82111. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82112. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82113. window.removeEventListener("resize", this._onResize);
  82114. document.body.removeChild(VirtualJoystick.vjCanvas);
  82115. VirtualJoystick.vjCanvas = null;
  82116. }
  82117. };
  82118. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82119. VirtualJoystick._globalJoystickIndex = 0;
  82120. return VirtualJoystick;
  82121. }());
  82122. BABYLON.VirtualJoystick = VirtualJoystick;
  82123. })(BABYLON || (BABYLON = {}));
  82124. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82125. var BABYLON;
  82126. (function (BABYLON) {
  82127. // We're mainly based on the logic defined into the FreeCamera code
  82128. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82129. __extends(VirtualJoysticksCamera, _super);
  82130. function VirtualJoysticksCamera(name, position, scene) {
  82131. var _this = _super.call(this, name, position, scene) || this;
  82132. _this.inputs.addVirtualJoystick();
  82133. return _this;
  82134. }
  82135. VirtualJoysticksCamera.prototype.getClassName = function () {
  82136. return "VirtualJoysticksCamera";
  82137. };
  82138. return VirtualJoysticksCamera;
  82139. }(BABYLON.FreeCamera));
  82140. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82141. })(BABYLON || (BABYLON = {}));
  82142. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82143. var BABYLON;
  82144. (function (BABYLON) {
  82145. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82146. function FreeCameraVirtualJoystickInput() {
  82147. }
  82148. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82149. return this._leftjoystick;
  82150. };
  82151. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82152. return this._rightjoystick;
  82153. };
  82154. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82155. if (this._leftjoystick) {
  82156. var camera = this.camera;
  82157. var speed = camera._computeLocalCameraSpeed() * 50;
  82158. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82159. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82160. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82161. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82162. if (!this._leftjoystick.pressed) {
  82163. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82164. }
  82165. if (!this._rightjoystick.pressed) {
  82166. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82167. }
  82168. }
  82169. };
  82170. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82171. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82172. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82173. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82174. this._leftjoystick.setJoystickSensibility(0.15);
  82175. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82176. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82177. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82178. this._rightjoystick.reverseUpDown = true;
  82179. this._rightjoystick.setJoystickSensibility(0.05);
  82180. this._rightjoystick.setJoystickColor("yellow");
  82181. };
  82182. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82183. this._leftjoystick.releaseCanvas();
  82184. this._rightjoystick.releaseCanvas();
  82185. };
  82186. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82187. return "FreeCameraVirtualJoystickInput";
  82188. };
  82189. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82190. return "virtualJoystick";
  82191. };
  82192. return FreeCameraVirtualJoystickInput;
  82193. }());
  82194. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82195. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82196. })(BABYLON || (BABYLON = {}));
  82197. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82198. var BABYLON;
  82199. (function (BABYLON) {
  82200. var SimplificationSettings = /** @class */ (function () {
  82201. function SimplificationSettings(quality, distance, optimizeMesh) {
  82202. this.quality = quality;
  82203. this.distance = distance;
  82204. this.optimizeMesh = optimizeMesh;
  82205. }
  82206. return SimplificationSettings;
  82207. }());
  82208. BABYLON.SimplificationSettings = SimplificationSettings;
  82209. var SimplificationQueue = /** @class */ (function () {
  82210. function SimplificationQueue() {
  82211. this.running = false;
  82212. this._simplificationArray = [];
  82213. }
  82214. SimplificationQueue.prototype.addTask = function (task) {
  82215. this._simplificationArray.push(task);
  82216. };
  82217. SimplificationQueue.prototype.executeNext = function () {
  82218. var task = this._simplificationArray.pop();
  82219. if (task) {
  82220. this.running = true;
  82221. this.runSimplification(task);
  82222. }
  82223. else {
  82224. this.running = false;
  82225. }
  82226. };
  82227. SimplificationQueue.prototype.runSimplification = function (task) {
  82228. var _this = this;
  82229. if (task.parallelProcessing) {
  82230. //parallel simplifier
  82231. task.settings.forEach(function (setting) {
  82232. var simplifier = _this.getSimplifier(task);
  82233. simplifier.simplify(setting, function (newMesh) {
  82234. task.mesh.addLODLevel(setting.distance, newMesh);
  82235. newMesh.isVisible = true;
  82236. //check if it is the last
  82237. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82238. //all done, run the success callback.
  82239. task.successCallback();
  82240. }
  82241. _this.executeNext();
  82242. });
  82243. });
  82244. }
  82245. else {
  82246. //single simplifier.
  82247. var simplifier = this.getSimplifier(task);
  82248. var runDecimation = function (setting, callback) {
  82249. simplifier.simplify(setting, function (newMesh) {
  82250. task.mesh.addLODLevel(setting.distance, newMesh);
  82251. newMesh.isVisible = true;
  82252. //run the next quality level
  82253. callback();
  82254. });
  82255. };
  82256. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82257. runDecimation(task.settings[loop.index], function () {
  82258. loop.executeNext();
  82259. });
  82260. }, function () {
  82261. //execution ended, run the success callback.
  82262. if (task.successCallback) {
  82263. task.successCallback();
  82264. }
  82265. _this.executeNext();
  82266. });
  82267. }
  82268. };
  82269. SimplificationQueue.prototype.getSimplifier = function (task) {
  82270. switch (task.simplificationType) {
  82271. case SimplificationType.QUADRATIC:
  82272. default:
  82273. return new QuadraticErrorSimplification(task.mesh);
  82274. }
  82275. };
  82276. return SimplificationQueue;
  82277. }());
  82278. BABYLON.SimplificationQueue = SimplificationQueue;
  82279. /**
  82280. * The implemented types of simplification.
  82281. * At the moment only Quadratic Error Decimation is implemented.
  82282. */
  82283. var SimplificationType;
  82284. (function (SimplificationType) {
  82285. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82286. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82287. var DecimationTriangle = /** @class */ (function () {
  82288. function DecimationTriangle(vertices) {
  82289. this.vertices = vertices;
  82290. this.error = new Array(4);
  82291. this.deleted = false;
  82292. this.isDirty = false;
  82293. this.deletePending = false;
  82294. this.borderFactor = 0;
  82295. }
  82296. return DecimationTriangle;
  82297. }());
  82298. BABYLON.DecimationTriangle = DecimationTriangle;
  82299. var DecimationVertex = /** @class */ (function () {
  82300. function DecimationVertex(position, id) {
  82301. this.position = position;
  82302. this.id = id;
  82303. this.isBorder = true;
  82304. this.q = new QuadraticMatrix();
  82305. this.triangleCount = 0;
  82306. this.triangleStart = 0;
  82307. this.originalOffsets = [];
  82308. }
  82309. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82310. this.position.copyFrom(newPosition);
  82311. };
  82312. return DecimationVertex;
  82313. }());
  82314. BABYLON.DecimationVertex = DecimationVertex;
  82315. var QuadraticMatrix = /** @class */ (function () {
  82316. function QuadraticMatrix(data) {
  82317. this.data = new Array(10);
  82318. for (var i = 0; i < 10; ++i) {
  82319. if (data && data[i]) {
  82320. this.data[i] = data[i];
  82321. }
  82322. else {
  82323. this.data[i] = 0;
  82324. }
  82325. }
  82326. }
  82327. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82328. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82329. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82330. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82331. return det;
  82332. };
  82333. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82334. for (var i = 0; i < 10; ++i) {
  82335. this.data[i] += matrix.data[i];
  82336. }
  82337. };
  82338. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82339. for (var i = 0; i < 10; ++i) {
  82340. this.data[i] += data[i];
  82341. }
  82342. };
  82343. QuadraticMatrix.prototype.add = function (matrix) {
  82344. var m = new QuadraticMatrix();
  82345. for (var i = 0; i < 10; ++i) {
  82346. m.data[i] = this.data[i] + matrix.data[i];
  82347. }
  82348. return m;
  82349. };
  82350. QuadraticMatrix.FromData = function (a, b, c, d) {
  82351. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82352. };
  82353. //returning an array to avoid garbage collection
  82354. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82355. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82356. };
  82357. return QuadraticMatrix;
  82358. }());
  82359. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82360. var Reference = /** @class */ (function () {
  82361. function Reference(vertexId, triangleId) {
  82362. this.vertexId = vertexId;
  82363. this.triangleId = triangleId;
  82364. }
  82365. return Reference;
  82366. }());
  82367. BABYLON.Reference = Reference;
  82368. /**
  82369. * An implementation of the Quadratic Error simplification algorithm.
  82370. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82371. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82372. * @author RaananW
  82373. */
  82374. var QuadraticErrorSimplification = /** @class */ (function () {
  82375. function QuadraticErrorSimplification(_mesh) {
  82376. this._mesh = _mesh;
  82377. this.syncIterations = 5000;
  82378. this.aggressiveness = 7;
  82379. this.decimationIterations = 100;
  82380. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82381. }
  82382. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82383. var _this = this;
  82384. this.initDecimatedMesh();
  82385. //iterating through the submeshes array, one after the other.
  82386. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82387. _this.initWithMesh(loop.index, function () {
  82388. _this.runDecimation(settings, loop.index, function () {
  82389. loop.executeNext();
  82390. });
  82391. }, settings.optimizeMesh);
  82392. }, function () {
  82393. setTimeout(function () {
  82394. successCallback(_this._reconstructedMesh);
  82395. }, 0);
  82396. });
  82397. };
  82398. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82399. var _this = this;
  82400. var targetCount = ~~(this.triangles.length * settings.quality);
  82401. var deletedTriangles = 0;
  82402. var triangleCount = this.triangles.length;
  82403. var iterationFunction = function (iteration, callback) {
  82404. setTimeout(function () {
  82405. if (iteration % 5 === 0) {
  82406. _this.updateMesh(iteration === 0);
  82407. }
  82408. for (var i = 0; i < _this.triangles.length; ++i) {
  82409. _this.triangles[i].isDirty = false;
  82410. }
  82411. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82412. var trianglesIterator = function (i) {
  82413. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82414. var t = _this.triangles[tIdx];
  82415. if (!t)
  82416. return;
  82417. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82418. return;
  82419. }
  82420. for (var j = 0; j < 3; ++j) {
  82421. if (t.error[j] < threshold) {
  82422. var deleted0 = [];
  82423. var deleted1 = [];
  82424. var v0 = t.vertices[j];
  82425. var v1 = t.vertices[(j + 1) % 3];
  82426. if (v0.isBorder || v1.isBorder)
  82427. continue;
  82428. var p = BABYLON.Vector3.Zero();
  82429. var n = BABYLON.Vector3.Zero();
  82430. var uv = BABYLON.Vector2.Zero();
  82431. var color = new BABYLON.Color4(0, 0, 0, 1);
  82432. _this.calculateError(v0, v1, p, n, uv, color);
  82433. var delTr = new Array();
  82434. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82435. continue;
  82436. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82437. continue;
  82438. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82439. continue;
  82440. var uniqueArray = new Array();
  82441. delTr.forEach(function (deletedT) {
  82442. if (uniqueArray.indexOf(deletedT) === -1) {
  82443. deletedT.deletePending = true;
  82444. uniqueArray.push(deletedT);
  82445. }
  82446. });
  82447. if (uniqueArray.length % 2 !== 0) {
  82448. continue;
  82449. }
  82450. v0.q = v1.q.add(v0.q);
  82451. v0.updatePosition(p);
  82452. var tStart = _this.references.length;
  82453. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82454. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82455. var tCount = _this.references.length - tStart;
  82456. if (tCount <= v0.triangleCount) {
  82457. if (tCount) {
  82458. for (var c = 0; c < tCount; c++) {
  82459. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82460. }
  82461. }
  82462. }
  82463. else {
  82464. v0.triangleStart = tStart;
  82465. }
  82466. v0.triangleCount = tCount;
  82467. break;
  82468. }
  82469. }
  82470. };
  82471. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82472. }, 0);
  82473. };
  82474. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82475. if (triangleCount - deletedTriangles <= targetCount)
  82476. loop.breakLoop();
  82477. else {
  82478. iterationFunction(loop.index, function () {
  82479. loop.executeNext();
  82480. });
  82481. }
  82482. }, function () {
  82483. setTimeout(function () {
  82484. //reconstruct this part of the mesh
  82485. _this.reconstructMesh(submeshIndex);
  82486. successCallback();
  82487. }, 0);
  82488. });
  82489. };
  82490. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82491. var _this = this;
  82492. this.vertices = [];
  82493. this.triangles = [];
  82494. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82495. var indices = this._mesh.getIndices();
  82496. var submesh = this._mesh.subMeshes[submeshIndex];
  82497. var findInVertices = function (positionToSearch) {
  82498. if (optimizeMesh) {
  82499. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82500. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82501. return _this.vertices[ii];
  82502. }
  82503. }
  82504. }
  82505. return null;
  82506. };
  82507. var vertexReferences = [];
  82508. var vertexInit = function (i) {
  82509. if (!positionData) {
  82510. return;
  82511. }
  82512. var offset = i + submesh.verticesStart;
  82513. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82514. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82515. vertex.originalOffsets.push(offset);
  82516. if (vertex.id === _this.vertices.length) {
  82517. _this.vertices.push(vertex);
  82518. }
  82519. vertexReferences.push(vertex.id);
  82520. };
  82521. //var totalVertices = mesh.getTotalVertices();
  82522. var totalVertices = submesh.verticesCount;
  82523. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82524. var indicesInit = function (i) {
  82525. if (!indices) {
  82526. return;
  82527. }
  82528. var offset = (submesh.indexStart / 3) + i;
  82529. var pos = (offset * 3);
  82530. var i0 = indices[pos + 0];
  82531. var i1 = indices[pos + 1];
  82532. var i2 = indices[pos + 2];
  82533. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82534. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82535. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82536. var triangle = new DecimationTriangle([v0, v1, v2]);
  82537. triangle.originalOffset = pos;
  82538. _this.triangles.push(triangle);
  82539. };
  82540. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82541. _this.init(callback);
  82542. });
  82543. });
  82544. };
  82545. QuadraticErrorSimplification.prototype.init = function (callback) {
  82546. var _this = this;
  82547. var triangleInit1 = function (i) {
  82548. var t = _this.triangles[i];
  82549. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82550. for (var j = 0; j < 3; j++) {
  82551. 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))));
  82552. }
  82553. };
  82554. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82555. var triangleInit2 = function (i) {
  82556. var t = _this.triangles[i];
  82557. for (var j = 0; j < 3; ++j) {
  82558. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82559. }
  82560. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82561. };
  82562. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82563. callback();
  82564. });
  82565. });
  82566. };
  82567. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82568. var newTriangles = [];
  82569. var i;
  82570. for (i = 0; i < this.vertices.length; ++i) {
  82571. this.vertices[i].triangleCount = 0;
  82572. }
  82573. var t;
  82574. var j;
  82575. for (i = 0; i < this.triangles.length; ++i) {
  82576. if (!this.triangles[i].deleted) {
  82577. t = this.triangles[i];
  82578. for (j = 0; j < 3; ++j) {
  82579. t.vertices[j].triangleCount = 1;
  82580. }
  82581. newTriangles.push(t);
  82582. }
  82583. }
  82584. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82585. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82586. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82587. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82588. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82589. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82590. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82591. var vertexCount = 0;
  82592. for (i = 0; i < this.vertices.length; ++i) {
  82593. var vertex = this.vertices[i];
  82594. vertex.id = vertexCount;
  82595. if (vertex.triangleCount) {
  82596. vertex.originalOffsets.forEach(function (originalOffset) {
  82597. if (!normalData) {
  82598. return;
  82599. }
  82600. newPositionData.push(vertex.position.x);
  82601. newPositionData.push(vertex.position.y);
  82602. newPositionData.push(vertex.position.z);
  82603. newNormalData.push(normalData[originalOffset * 3]);
  82604. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82605. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82606. if (uvs && uvs.length) {
  82607. newUVsData.push(uvs[(originalOffset * 2)]);
  82608. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82609. }
  82610. else if (colorsData && colorsData.length) {
  82611. newColorsData.push(colorsData[(originalOffset * 4)]);
  82612. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82613. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82614. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82615. }
  82616. ++vertexCount;
  82617. });
  82618. }
  82619. }
  82620. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82621. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82622. var submeshesArray = this._reconstructedMesh.subMeshes;
  82623. this._reconstructedMesh.subMeshes = [];
  82624. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82625. var originalIndices = this._mesh.getIndices();
  82626. for (i = 0; i < newTriangles.length; ++i) {
  82627. t = newTriangles[i]; //now get the new referencing point for each vertex
  82628. [0, 1, 2].forEach(function (idx) {
  82629. var id = originalIndices[t.originalOffset + idx];
  82630. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82631. if (offset < 0)
  82632. offset = 0;
  82633. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82634. });
  82635. }
  82636. //overwriting the old vertex buffers and indices.
  82637. this._reconstructedMesh.setIndices(newIndicesArray);
  82638. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82639. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82640. if (newUVsData.length > 0)
  82641. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82642. if (newColorsData.length > 0)
  82643. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82644. //create submesh
  82645. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82646. if (submeshIndex > 0) {
  82647. this._reconstructedMesh.subMeshes = [];
  82648. submeshesArray.forEach(function (submesh) {
  82649. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82650. });
  82651. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82652. }
  82653. };
  82654. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82655. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82656. this._reconstructedMesh.material = this._mesh.material;
  82657. this._reconstructedMesh.parent = this._mesh.parent;
  82658. this._reconstructedMesh.isVisible = false;
  82659. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82660. };
  82661. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82662. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82663. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82664. if (t.deleted)
  82665. continue;
  82666. var s = this.references[vertex1.triangleStart + i].vertexId;
  82667. var v1 = t.vertices[(s + 1) % 3];
  82668. var v2 = t.vertices[(s + 2) % 3];
  82669. if ((v1 === vertex2 || v2 === vertex2)) {
  82670. deletedArray[i] = true;
  82671. delTr.push(t);
  82672. continue;
  82673. }
  82674. var d1 = v1.position.subtract(point);
  82675. d1 = d1.normalize();
  82676. var d2 = v2.position.subtract(point);
  82677. d2 = d2.normalize();
  82678. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82679. return true;
  82680. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82681. deletedArray[i] = false;
  82682. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82683. return true;
  82684. }
  82685. return false;
  82686. };
  82687. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82688. var newDeleted = deletedTriangles;
  82689. for (var i = 0; i < vertex.triangleCount; ++i) {
  82690. var ref = this.references[vertex.triangleStart + i];
  82691. var t = this.triangles[ref.triangleId];
  82692. if (t.deleted)
  82693. continue;
  82694. if (deletedArray[i] && t.deletePending) {
  82695. t.deleted = true;
  82696. newDeleted++;
  82697. continue;
  82698. }
  82699. t.vertices[ref.vertexId] = origVertex;
  82700. t.isDirty = true;
  82701. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82702. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82703. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82704. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82705. this.references.push(ref);
  82706. }
  82707. return newDeleted;
  82708. };
  82709. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82710. for (var i = 0; i < this.vertices.length; ++i) {
  82711. var vCount = [];
  82712. var vId = [];
  82713. var v = this.vertices[i];
  82714. var j;
  82715. for (j = 0; j < v.triangleCount; ++j) {
  82716. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82717. for (var ii = 0; ii < 3; ii++) {
  82718. var ofs = 0;
  82719. var vv = triangle.vertices[ii];
  82720. while (ofs < vCount.length) {
  82721. if (vId[ofs] === vv.id)
  82722. break;
  82723. ++ofs;
  82724. }
  82725. if (ofs === vCount.length) {
  82726. vCount.push(1);
  82727. vId.push(vv.id);
  82728. }
  82729. else {
  82730. vCount[ofs]++;
  82731. }
  82732. }
  82733. }
  82734. for (j = 0; j < vCount.length; ++j) {
  82735. if (vCount[j] === 1) {
  82736. this.vertices[vId[j]].isBorder = true;
  82737. }
  82738. else {
  82739. this.vertices[vId[j]].isBorder = false;
  82740. }
  82741. }
  82742. }
  82743. };
  82744. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82745. if (identifyBorders === void 0) { identifyBorders = false; }
  82746. var i;
  82747. if (!identifyBorders) {
  82748. var newTrianglesVector = [];
  82749. for (i = 0; i < this.triangles.length; ++i) {
  82750. if (!this.triangles[i].deleted) {
  82751. newTrianglesVector.push(this.triangles[i]);
  82752. }
  82753. }
  82754. this.triangles = newTrianglesVector;
  82755. }
  82756. for (i = 0; i < this.vertices.length; ++i) {
  82757. this.vertices[i].triangleCount = 0;
  82758. this.vertices[i].triangleStart = 0;
  82759. }
  82760. var t;
  82761. var j;
  82762. var v;
  82763. for (i = 0; i < this.triangles.length; ++i) {
  82764. t = this.triangles[i];
  82765. for (j = 0; j < 3; ++j) {
  82766. v = t.vertices[j];
  82767. v.triangleCount++;
  82768. }
  82769. }
  82770. var tStart = 0;
  82771. for (i = 0; i < this.vertices.length; ++i) {
  82772. this.vertices[i].triangleStart = tStart;
  82773. tStart += this.vertices[i].triangleCount;
  82774. this.vertices[i].triangleCount = 0;
  82775. }
  82776. var newReferences = new Array(this.triangles.length * 3);
  82777. for (i = 0; i < this.triangles.length; ++i) {
  82778. t = this.triangles[i];
  82779. for (j = 0; j < 3; ++j) {
  82780. v = t.vertices[j];
  82781. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82782. v.triangleCount++;
  82783. }
  82784. }
  82785. this.references = newReferences;
  82786. if (identifyBorders) {
  82787. this.identifyBorder();
  82788. }
  82789. };
  82790. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82791. var x = point.x;
  82792. var y = point.y;
  82793. var z = point.z;
  82794. 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
  82795. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82796. };
  82797. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82798. var q = vertex1.q.add(vertex2.q);
  82799. var border = vertex1.isBorder && vertex2.isBorder;
  82800. var error = 0;
  82801. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82802. if (qDet !== 0 && !border) {
  82803. if (!pointResult) {
  82804. pointResult = BABYLON.Vector3.Zero();
  82805. }
  82806. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82807. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82808. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82809. error = this.vertexError(q, pointResult);
  82810. }
  82811. else {
  82812. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82813. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82814. var error1 = this.vertexError(q, vertex1.position);
  82815. var error2 = this.vertexError(q, vertex2.position);
  82816. var error3 = this.vertexError(q, p3);
  82817. error = Math.min(error1, error2, error3);
  82818. if (error === error1) {
  82819. if (pointResult) {
  82820. pointResult.copyFrom(vertex1.position);
  82821. }
  82822. }
  82823. else if (error === error2) {
  82824. if (pointResult) {
  82825. pointResult.copyFrom(vertex2.position);
  82826. }
  82827. }
  82828. else {
  82829. if (pointResult) {
  82830. pointResult.copyFrom(p3);
  82831. }
  82832. }
  82833. }
  82834. return error;
  82835. };
  82836. return QuadraticErrorSimplification;
  82837. }());
  82838. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82839. })(BABYLON || (BABYLON = {}));
  82840. //# sourceMappingURL=babylon.meshSimplification.js.map
  82841. var BABYLON;
  82842. (function (BABYLON) {
  82843. var MeshLODLevel = /** @class */ (function () {
  82844. function MeshLODLevel(distance, mesh) {
  82845. this.distance = distance;
  82846. this.mesh = mesh;
  82847. }
  82848. return MeshLODLevel;
  82849. }());
  82850. BABYLON.MeshLODLevel = MeshLODLevel;
  82851. })(BABYLON || (BABYLON = {}));
  82852. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82853. var BABYLON;
  82854. (function (BABYLON) {
  82855. /**
  82856. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82857. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82858. */
  82859. var SceneOptimization = /** @class */ (function () {
  82860. /**
  82861. * Creates the SceneOptimization object
  82862. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82863. * @param desc defines the description associated with the optimization
  82864. */
  82865. function SceneOptimization(
  82866. /**
  82867. * Defines the priority of this optimization (0 by default which means first in the list)
  82868. */
  82869. priority) {
  82870. if (priority === void 0) { priority = 0; }
  82871. this.priority = priority;
  82872. }
  82873. /**
  82874. * Gets a string describing the action executed by the current optimization
  82875. * @returns description string
  82876. */
  82877. SceneOptimization.prototype.getDescription = function () {
  82878. return "";
  82879. };
  82880. /**
  82881. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82882. * @param scene defines the current scene where to apply this optimization
  82883. * @param optimizer defines the current optimizer
  82884. * @returns true if everything that can be done was applied
  82885. */
  82886. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82887. return true;
  82888. };
  82889. ;
  82890. return SceneOptimization;
  82891. }());
  82892. BABYLON.SceneOptimization = SceneOptimization;
  82893. /**
  82894. * Defines an optimization used to reduce the size of render target textures
  82895. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82896. */
  82897. var TextureOptimization = /** @class */ (function (_super) {
  82898. __extends(TextureOptimization, _super);
  82899. /**
  82900. * Creates the TextureOptimization object
  82901. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82902. * @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
  82903. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82904. */
  82905. function TextureOptimization(
  82906. /**
  82907. * Defines the priority of this optimization (0 by default which means first in the list)
  82908. */
  82909. priority,
  82910. /**
  82911. * 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
  82912. */
  82913. maximumSize,
  82914. /**
  82915. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82916. */
  82917. step) {
  82918. if (priority === void 0) { priority = 0; }
  82919. if (maximumSize === void 0) { maximumSize = 1024; }
  82920. if (step === void 0) { step = 0.5; }
  82921. var _this = _super.call(this, priority) || this;
  82922. _this.priority = priority;
  82923. _this.maximumSize = maximumSize;
  82924. _this.step = step;
  82925. return _this;
  82926. }
  82927. /**
  82928. * Gets a string describing the action executed by the current optimization
  82929. * @returns description string
  82930. */
  82931. TextureOptimization.prototype.getDescription = function () {
  82932. return "Reducing render target texture size to " + this.maximumSize;
  82933. };
  82934. /**
  82935. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82936. * @param scene defines the current scene where to apply this optimization
  82937. * @param optimizer defines the current optimizer
  82938. * @returns true if everything that can be done was applied
  82939. */
  82940. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82941. var allDone = true;
  82942. for (var index = 0; index < scene.textures.length; index++) {
  82943. var texture = scene.textures[index];
  82944. if (!texture.canRescale || texture.getContext) {
  82945. continue;
  82946. }
  82947. var currentSize = texture.getSize();
  82948. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82949. if (maxDimension > this.maximumSize) {
  82950. texture.scale(this.step);
  82951. allDone = false;
  82952. }
  82953. }
  82954. return allDone;
  82955. };
  82956. return TextureOptimization;
  82957. }(SceneOptimization));
  82958. BABYLON.TextureOptimization = TextureOptimization;
  82959. /**
  82960. * Defines an optimization used to increase or decrease the rendering resolution
  82961. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82962. */
  82963. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82964. __extends(HardwareScalingOptimization, _super);
  82965. /**
  82966. * Creates the HardwareScalingOptimization object
  82967. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82968. * @param maximumScale defines the maximum scale to use (2 by default)
  82969. * @param step defines the step to use between two passes (0.5 by default)
  82970. */
  82971. function HardwareScalingOptimization(
  82972. /**
  82973. * Defines the priority of this optimization (0 by default which means first in the list)
  82974. */
  82975. priority,
  82976. /**
  82977. * Defines the maximum scale to use (2 by default)
  82978. */
  82979. maximumScale,
  82980. /**
  82981. * Defines the step to use between two passes (0.5 by default)
  82982. */
  82983. step) {
  82984. if (priority === void 0) { priority = 0; }
  82985. if (maximumScale === void 0) { maximumScale = 2; }
  82986. if (step === void 0) { step = 0.25; }
  82987. var _this = _super.call(this, priority) || this;
  82988. _this.priority = priority;
  82989. _this.maximumScale = maximumScale;
  82990. _this.step = step;
  82991. _this._currentScale = -1;
  82992. _this._directionOffset = 1;
  82993. return _this;
  82994. }
  82995. /**
  82996. * Gets a string describing the action executed by the current optimization
  82997. * @return description string
  82998. */
  82999. HardwareScalingOptimization.prototype.getDescription = function () {
  83000. return "Setting hardware scaling level to " + this._currentScale;
  83001. };
  83002. /**
  83003. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83004. * @param scene defines the current scene where to apply this optimization
  83005. * @param optimizer defines the current optimizer
  83006. * @returns true if everything that can be done was applied
  83007. */
  83008. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83009. if (this._currentScale === -1) {
  83010. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83011. if (this._currentScale > this.maximumScale) {
  83012. this._directionOffset = -1;
  83013. }
  83014. }
  83015. this._currentScale += this._directionOffset * this.step;
  83016. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83017. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83018. };
  83019. ;
  83020. return HardwareScalingOptimization;
  83021. }(SceneOptimization));
  83022. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83023. /**
  83024. * Defines an optimization used to remove shadows
  83025. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83026. */
  83027. var ShadowsOptimization = /** @class */ (function (_super) {
  83028. __extends(ShadowsOptimization, _super);
  83029. function ShadowsOptimization() {
  83030. return _super !== null && _super.apply(this, arguments) || this;
  83031. }
  83032. /**
  83033. * Gets a string describing the action executed by the current optimization
  83034. * @return description string
  83035. */
  83036. ShadowsOptimization.prototype.getDescription = function () {
  83037. return "Turning shadows on/off";
  83038. };
  83039. /**
  83040. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83041. * @param scene defines the current scene where to apply this optimization
  83042. * @param optimizer defines the current optimizer
  83043. * @returns true if everything that can be done was applied
  83044. */
  83045. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83046. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83047. return true;
  83048. };
  83049. ;
  83050. return ShadowsOptimization;
  83051. }(SceneOptimization));
  83052. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83053. /**
  83054. * Defines an optimization used to turn post-processes off
  83055. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83056. */
  83057. var PostProcessesOptimization = /** @class */ (function (_super) {
  83058. __extends(PostProcessesOptimization, _super);
  83059. function PostProcessesOptimization() {
  83060. return _super !== null && _super.apply(this, arguments) || this;
  83061. }
  83062. /**
  83063. * Gets a string describing the action executed by the current optimization
  83064. * @return description string
  83065. */
  83066. PostProcessesOptimization.prototype.getDescription = function () {
  83067. return "Turning post-processes on/off";
  83068. };
  83069. /**
  83070. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83071. * @param scene defines the current scene where to apply this optimization
  83072. * @param optimizer defines the current optimizer
  83073. * @returns true if everything that can be done was applied
  83074. */
  83075. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83076. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83077. return true;
  83078. };
  83079. ;
  83080. return PostProcessesOptimization;
  83081. }(SceneOptimization));
  83082. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83083. /**
  83084. * Defines an optimization used to turn lens flares off
  83085. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83086. */
  83087. var LensFlaresOptimization = /** @class */ (function (_super) {
  83088. __extends(LensFlaresOptimization, _super);
  83089. function LensFlaresOptimization() {
  83090. return _super !== null && _super.apply(this, arguments) || this;
  83091. }
  83092. /**
  83093. * Gets a string describing the action executed by the current optimization
  83094. * @return description string
  83095. */
  83096. LensFlaresOptimization.prototype.getDescription = function () {
  83097. return "Turning lens flares on/off";
  83098. };
  83099. /**
  83100. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83101. * @param scene defines the current scene where to apply this optimization
  83102. * @param optimizer defines the current optimizer
  83103. * @returns true if everything that can be done was applied
  83104. */
  83105. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83106. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83107. return true;
  83108. };
  83109. ;
  83110. return LensFlaresOptimization;
  83111. }(SceneOptimization));
  83112. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83113. /**
  83114. * Defines an optimization based on user defined callback.
  83115. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83116. */
  83117. var CustomOptimization = /** @class */ (function (_super) {
  83118. __extends(CustomOptimization, _super);
  83119. function CustomOptimization() {
  83120. return _super !== null && _super.apply(this, arguments) || this;
  83121. }
  83122. /**
  83123. * Gets a string describing the action executed by the current optimization
  83124. * @returns description string
  83125. */
  83126. CustomOptimization.prototype.getDescription = function () {
  83127. if (this.onGetDescription) {
  83128. return this.onGetDescription();
  83129. }
  83130. return "Running user defined callback";
  83131. };
  83132. /**
  83133. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83134. * @param scene defines the current scene where to apply this optimization
  83135. * @param optimizer defines the current optimizer
  83136. * @returns true if everything that can be done was applied
  83137. */
  83138. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83139. if (this.onApply) {
  83140. return this.onApply(scene, optimizer);
  83141. }
  83142. return true;
  83143. };
  83144. ;
  83145. return CustomOptimization;
  83146. }(SceneOptimization));
  83147. BABYLON.CustomOptimization = CustomOptimization;
  83148. /**
  83149. * Defines an optimization used to turn particles off
  83150. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83151. */
  83152. var ParticlesOptimization = /** @class */ (function (_super) {
  83153. __extends(ParticlesOptimization, _super);
  83154. function ParticlesOptimization() {
  83155. return _super !== null && _super.apply(this, arguments) || this;
  83156. }
  83157. /**
  83158. * Gets a string describing the action executed by the current optimization
  83159. * @return description string
  83160. */
  83161. ParticlesOptimization.prototype.getDescription = function () {
  83162. return "Turning particles on/off";
  83163. };
  83164. /**
  83165. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83166. * @param scene defines the current scene where to apply this optimization
  83167. * @param optimizer defines the current optimizer
  83168. * @returns true if everything that can be done was applied
  83169. */
  83170. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83171. scene.particlesEnabled = optimizer.isInImprovementMode;
  83172. return true;
  83173. };
  83174. ;
  83175. return ParticlesOptimization;
  83176. }(SceneOptimization));
  83177. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83178. /**
  83179. * Defines an optimization used to turn render targets off
  83180. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83181. */
  83182. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83183. __extends(RenderTargetsOptimization, _super);
  83184. function RenderTargetsOptimization() {
  83185. return _super !== null && _super.apply(this, arguments) || this;
  83186. }
  83187. /**
  83188. * Gets a string describing the action executed by the current optimization
  83189. * @return description string
  83190. */
  83191. RenderTargetsOptimization.prototype.getDescription = function () {
  83192. return "Turning render targets off";
  83193. };
  83194. /**
  83195. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83196. * @param scene defines the current scene where to apply this optimization
  83197. * @param optimizer defines the current optimizer
  83198. * @returns true if everything that can be done was applied
  83199. */
  83200. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83201. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83202. return true;
  83203. };
  83204. ;
  83205. return RenderTargetsOptimization;
  83206. }(SceneOptimization));
  83207. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83208. /**
  83209. * Defines an optimization used to merge meshes with compatible materials
  83210. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83211. */
  83212. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83213. __extends(MergeMeshesOptimization, _super);
  83214. function MergeMeshesOptimization() {
  83215. var _this = _super !== null && _super.apply(this, arguments) || this;
  83216. _this._canBeMerged = function (abstractMesh) {
  83217. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83218. return false;
  83219. }
  83220. var mesh = abstractMesh;
  83221. if (!mesh.isVisible || !mesh.isEnabled()) {
  83222. return false;
  83223. }
  83224. if (mesh.instances.length > 0) {
  83225. return false;
  83226. }
  83227. if (mesh.skeleton || mesh.hasLODLevels) {
  83228. return false;
  83229. }
  83230. if (mesh.parent) {
  83231. return false;
  83232. }
  83233. return true;
  83234. };
  83235. return _this;
  83236. }
  83237. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83238. /**
  83239. * Gets or sets a boolean which defines if optimization octree has to be updated
  83240. */
  83241. get: function () {
  83242. return MergeMeshesOptimization._UpdateSelectionTree;
  83243. },
  83244. /**
  83245. * Gets or sets a boolean which defines if optimization octree has to be updated
  83246. */
  83247. set: function (value) {
  83248. MergeMeshesOptimization._UpdateSelectionTree = value;
  83249. },
  83250. enumerable: true,
  83251. configurable: true
  83252. });
  83253. /**
  83254. * Gets a string describing the action executed by the current optimization
  83255. * @return description string
  83256. */
  83257. MergeMeshesOptimization.prototype.getDescription = function () {
  83258. return "Merging similar meshes together";
  83259. };
  83260. /**
  83261. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83262. * @param scene defines the current scene where to apply this optimization
  83263. * @param optimizer defines the current optimizer
  83264. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83265. * @returns true if everything that can be done was applied
  83266. */
  83267. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83268. var globalPool = scene.meshes.slice(0);
  83269. var globalLength = globalPool.length;
  83270. for (var index = 0; index < globalLength; index++) {
  83271. var currentPool = new Array();
  83272. var current = globalPool[index];
  83273. // Checks
  83274. if (!this._canBeMerged(current)) {
  83275. continue;
  83276. }
  83277. currentPool.push(current);
  83278. // Find compatible meshes
  83279. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83280. var otherMesh = globalPool[subIndex];
  83281. if (!this._canBeMerged(otherMesh)) {
  83282. continue;
  83283. }
  83284. if (otherMesh.material !== current.material) {
  83285. continue;
  83286. }
  83287. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83288. continue;
  83289. }
  83290. currentPool.push(otherMesh);
  83291. globalLength--;
  83292. globalPool.splice(subIndex, 1);
  83293. subIndex--;
  83294. }
  83295. if (currentPool.length < 2) {
  83296. continue;
  83297. }
  83298. // Merge meshes
  83299. BABYLON.Mesh.MergeMeshes(currentPool);
  83300. }
  83301. if (updateSelectionTree != undefined) {
  83302. if (updateSelectionTree) {
  83303. scene.createOrUpdateSelectionOctree();
  83304. }
  83305. }
  83306. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83307. scene.createOrUpdateSelectionOctree();
  83308. }
  83309. return true;
  83310. };
  83311. ;
  83312. MergeMeshesOptimization._UpdateSelectionTree = false;
  83313. return MergeMeshesOptimization;
  83314. }(SceneOptimization));
  83315. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83316. /**
  83317. * Defines a list of options used by SceneOptimizer
  83318. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83319. */
  83320. var SceneOptimizerOptions = /** @class */ (function () {
  83321. /**
  83322. * Creates a new list of options used by SceneOptimizer
  83323. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83324. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83325. */
  83326. function SceneOptimizerOptions(
  83327. /**
  83328. * Defines the target frame rate to reach (60 by default)
  83329. */
  83330. targetFrameRate,
  83331. /**
  83332. * Defines the interval between two checkes (2000ms by default)
  83333. */
  83334. trackerDuration) {
  83335. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83336. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83337. this.targetFrameRate = targetFrameRate;
  83338. this.trackerDuration = trackerDuration;
  83339. /**
  83340. * Gets the list of optimizations to apply
  83341. */
  83342. this.optimizations = new Array();
  83343. }
  83344. /**
  83345. * Add a new optimization
  83346. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83347. * @returns the current SceneOptimizerOptions
  83348. */
  83349. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83350. this.optimizations.push(optimization);
  83351. return this;
  83352. };
  83353. /**
  83354. * Add a new custom optimization
  83355. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83356. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83357. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83358. * @returns the current SceneOptimizerOptions
  83359. */
  83360. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83361. if (priority === void 0) { priority = 0; }
  83362. var optimization = new CustomOptimization(priority);
  83363. optimization.onApply = onApply;
  83364. optimization.onGetDescription = onGetDescription;
  83365. this.optimizations.push(optimization);
  83366. return this;
  83367. };
  83368. /**
  83369. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83370. * @param targetFrameRate defines the target frame rate (60 by default)
  83371. * @returns a SceneOptimizerOptions object
  83372. */
  83373. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83374. var result = new SceneOptimizerOptions(targetFrameRate);
  83375. var priority = 0;
  83376. result.addOptimization(new MergeMeshesOptimization(priority));
  83377. result.addOptimization(new ShadowsOptimization(priority));
  83378. result.addOptimization(new LensFlaresOptimization(priority));
  83379. // Next priority
  83380. priority++;
  83381. result.addOptimization(new PostProcessesOptimization(priority));
  83382. result.addOptimization(new ParticlesOptimization(priority));
  83383. // Next priority
  83384. priority++;
  83385. result.addOptimization(new TextureOptimization(priority, 1024));
  83386. return result;
  83387. };
  83388. /**
  83389. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83390. * @param targetFrameRate defines the target frame rate (60 by default)
  83391. * @returns a SceneOptimizerOptions object
  83392. */
  83393. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83394. var result = new SceneOptimizerOptions(targetFrameRate);
  83395. var priority = 0;
  83396. result.addOptimization(new MergeMeshesOptimization(priority));
  83397. result.addOptimization(new ShadowsOptimization(priority));
  83398. result.addOptimization(new LensFlaresOptimization(priority));
  83399. // Next priority
  83400. priority++;
  83401. result.addOptimization(new PostProcessesOptimization(priority));
  83402. result.addOptimization(new ParticlesOptimization(priority));
  83403. // Next priority
  83404. priority++;
  83405. result.addOptimization(new TextureOptimization(priority, 512));
  83406. // Next priority
  83407. priority++;
  83408. result.addOptimization(new RenderTargetsOptimization(priority));
  83409. // Next priority
  83410. priority++;
  83411. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83412. return result;
  83413. };
  83414. /**
  83415. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83416. * @param targetFrameRate defines the target frame rate (60 by default)
  83417. * @returns a SceneOptimizerOptions object
  83418. */
  83419. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83420. var result = new SceneOptimizerOptions(targetFrameRate);
  83421. var priority = 0;
  83422. result.addOptimization(new MergeMeshesOptimization(priority));
  83423. result.addOptimization(new ShadowsOptimization(priority));
  83424. result.addOptimization(new LensFlaresOptimization(priority));
  83425. // Next priority
  83426. priority++;
  83427. result.addOptimization(new PostProcessesOptimization(priority));
  83428. result.addOptimization(new ParticlesOptimization(priority));
  83429. // Next priority
  83430. priority++;
  83431. result.addOptimization(new TextureOptimization(priority, 256));
  83432. // Next priority
  83433. priority++;
  83434. result.addOptimization(new RenderTargetsOptimization(priority));
  83435. // Next priority
  83436. priority++;
  83437. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83438. return result;
  83439. };
  83440. return SceneOptimizerOptions;
  83441. }());
  83442. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83443. /**
  83444. * Class used to run optimizations in order to reach a target frame rate
  83445. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83446. */
  83447. var SceneOptimizer = /** @class */ (function () {
  83448. /**
  83449. * Creates a new SceneOptimizer
  83450. * @param scene defines the scene to work on
  83451. * @param options defines the options to use with the SceneOptimizer
  83452. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83453. * @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)
  83454. */
  83455. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83456. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83457. if (improvementMode === void 0) { improvementMode = false; }
  83458. var _this = this;
  83459. this._isRunning = false;
  83460. this._currentPriorityLevel = 0;
  83461. this._targetFrameRate = 60;
  83462. this._trackerDuration = 2000;
  83463. this._currentFrameRate = 0;
  83464. this._improvementMode = false;
  83465. /**
  83466. * Defines an observable called when the optimizer reaches the target frame rate
  83467. */
  83468. this.onSuccessObservable = new BABYLON.Observable();
  83469. /**
  83470. * Defines an observable called when the optimizer enables an optimization
  83471. */
  83472. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83473. /**
  83474. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83475. */
  83476. this.onFailureObservable = new BABYLON.Observable();
  83477. if (!options) {
  83478. this._options = new SceneOptimizerOptions();
  83479. }
  83480. else {
  83481. this._options = options;
  83482. }
  83483. if (this._options.targetFrameRate) {
  83484. this._targetFrameRate = this._options.targetFrameRate;
  83485. }
  83486. if (this._options.trackerDuration) {
  83487. this._trackerDuration = this._options.trackerDuration;
  83488. }
  83489. if (autoGeneratePriorities) {
  83490. var priority = 0;
  83491. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83492. var optim = _a[_i];
  83493. optim.priority = priority++;
  83494. }
  83495. }
  83496. this._improvementMode = improvementMode;
  83497. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83498. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83499. _this._sceneDisposeObserver = null;
  83500. _this.dispose();
  83501. });
  83502. }
  83503. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83504. /**
  83505. * Gets a boolean indicating if the optimizer is in improvement mode
  83506. */
  83507. get: function () {
  83508. return this._improvementMode;
  83509. },
  83510. enumerable: true,
  83511. configurable: true
  83512. });
  83513. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83514. /**
  83515. * Gets the current priority level (0 at start)
  83516. */
  83517. get: function () {
  83518. return this._currentPriorityLevel;
  83519. },
  83520. enumerable: true,
  83521. configurable: true
  83522. });
  83523. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83524. /**
  83525. * Gets the current frame rate checked by the SceneOptimizer
  83526. */
  83527. get: function () {
  83528. return this._currentFrameRate;
  83529. },
  83530. enumerable: true,
  83531. configurable: true
  83532. });
  83533. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83534. /**
  83535. * Gets or sets the current target frame rate (60 by default)
  83536. */
  83537. get: function () {
  83538. return this._targetFrameRate;
  83539. },
  83540. /**
  83541. * Gets or sets the current target frame rate (60 by default)
  83542. */
  83543. set: function (value) {
  83544. this._targetFrameRate = value;
  83545. },
  83546. enumerable: true,
  83547. configurable: true
  83548. });
  83549. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83550. /**
  83551. * Gets or sets the current interval between two checks (every 2000ms by default)
  83552. */
  83553. get: function () {
  83554. return this._trackerDuration;
  83555. },
  83556. /**
  83557. * Gets or sets the current interval between two checks (every 2000ms by default)
  83558. */
  83559. set: function (value) {
  83560. this._trackerDuration = value;
  83561. },
  83562. enumerable: true,
  83563. configurable: true
  83564. });
  83565. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83566. /**
  83567. * Gets the list of active optimizations
  83568. */
  83569. get: function () {
  83570. return this._options.optimizations;
  83571. },
  83572. enumerable: true,
  83573. configurable: true
  83574. });
  83575. /**
  83576. * Stops the current optimizer
  83577. */
  83578. SceneOptimizer.prototype.stop = function () {
  83579. this._isRunning = false;
  83580. };
  83581. /**
  83582. * Reset the optimizer to initial step (current priority level = 0)
  83583. */
  83584. SceneOptimizer.prototype.reset = function () {
  83585. this._currentPriorityLevel = 0;
  83586. };
  83587. /**
  83588. * Start the optimizer. By default it will try to reach a specific framerate
  83589. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83590. */
  83591. SceneOptimizer.prototype.start = function () {
  83592. var _this = this;
  83593. if (this._isRunning) {
  83594. return;
  83595. }
  83596. this._isRunning = true;
  83597. // Let's wait for the scene to be ready before running our check
  83598. this._scene.executeWhenReady(function () {
  83599. setTimeout(function () {
  83600. _this._checkCurrentState();
  83601. }, _this._trackerDuration);
  83602. });
  83603. };
  83604. SceneOptimizer.prototype._checkCurrentState = function () {
  83605. var _this = this;
  83606. if (!this._isRunning) {
  83607. return;
  83608. }
  83609. var scene = this._scene;
  83610. var options = this._options;
  83611. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83612. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83613. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83614. this._isRunning = false;
  83615. this.onSuccessObservable.notifyObservers(this);
  83616. return;
  83617. }
  83618. // Apply current level of optimizations
  83619. var allDone = true;
  83620. var noOptimizationApplied = true;
  83621. for (var index = 0; index < options.optimizations.length; index++) {
  83622. var optimization = options.optimizations[index];
  83623. if (optimization.priority === this._currentPriorityLevel) {
  83624. noOptimizationApplied = false;
  83625. allDone = allDone && optimization.apply(scene, this);
  83626. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83627. }
  83628. }
  83629. // If no optimization was applied, this is a failure :(
  83630. if (noOptimizationApplied) {
  83631. this._isRunning = false;
  83632. this.onFailureObservable.notifyObservers(this);
  83633. return;
  83634. }
  83635. // If all optimizations were done, move to next level
  83636. if (allDone) {
  83637. this._currentPriorityLevel++;
  83638. }
  83639. // Let's the system running for a specific amount of time before checking FPS
  83640. scene.executeWhenReady(function () {
  83641. setTimeout(function () {
  83642. _this._checkCurrentState();
  83643. }, _this._trackerDuration);
  83644. });
  83645. };
  83646. /**
  83647. * Release all resources
  83648. */
  83649. SceneOptimizer.prototype.dispose = function () {
  83650. this.stop();
  83651. this.onSuccessObservable.clear();
  83652. this.onFailureObservable.clear();
  83653. this.onNewOptimizationAppliedObservable.clear();
  83654. if (this._sceneDisposeObserver) {
  83655. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83656. }
  83657. };
  83658. /**
  83659. * Helper function to create a SceneOptimizer with one single line of code
  83660. * @param scene defines the scene to work on
  83661. * @param options defines the options to use with the SceneOptimizer
  83662. * @param onSuccess defines a callback to call on success
  83663. * @param onFailure defines a callback to call on failure
  83664. * @returns the new SceneOptimizer object
  83665. */
  83666. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83667. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83668. if (onSuccess) {
  83669. optimizer.onSuccessObservable.add(function () {
  83670. onSuccess();
  83671. });
  83672. }
  83673. if (onFailure) {
  83674. optimizer.onFailureObservable.add(function () {
  83675. onFailure();
  83676. });
  83677. }
  83678. optimizer.start();
  83679. return optimizer;
  83680. };
  83681. return SceneOptimizer;
  83682. }());
  83683. BABYLON.SceneOptimizer = SceneOptimizer;
  83684. })(BABYLON || (BABYLON = {}));
  83685. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83686. var BABYLON;
  83687. (function (BABYLON) {
  83688. var OutlineRenderer = /** @class */ (function () {
  83689. function OutlineRenderer(scene) {
  83690. this.zOffset = 1;
  83691. this._scene = scene;
  83692. }
  83693. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83694. var _this = this;
  83695. if (useOverlay === void 0) { useOverlay = false; }
  83696. var scene = this._scene;
  83697. var engine = this._scene.getEngine();
  83698. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83699. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83700. return;
  83701. }
  83702. var mesh = subMesh.getRenderingMesh();
  83703. var material = subMesh.getMaterial();
  83704. if (!material || !scene.activeCamera) {
  83705. return;
  83706. }
  83707. engine.enableEffect(this._effect);
  83708. // Logarithmic depth
  83709. if (material.useLogarithmicDepth) {
  83710. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83711. }
  83712. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83713. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83714. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83715. // Bones
  83716. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83717. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83718. }
  83719. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83720. // Alpha test
  83721. if (material && material.needAlphaTesting()) {
  83722. var alphaTexture = material.getAlphaTestTexture();
  83723. if (alphaTexture) {
  83724. this._effect.setTexture("diffuseSampler", alphaTexture);
  83725. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83726. }
  83727. }
  83728. engine.setZOffset(-this.zOffset);
  83729. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83730. engine.setZOffset(0);
  83731. };
  83732. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83733. var defines = [];
  83734. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83735. var mesh = subMesh.getMesh();
  83736. var material = subMesh.getMaterial();
  83737. if (material) {
  83738. // Alpha test
  83739. if (material.needAlphaTesting()) {
  83740. defines.push("#define ALPHATEST");
  83741. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83742. attribs.push(BABYLON.VertexBuffer.UVKind);
  83743. defines.push("#define UV1");
  83744. }
  83745. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83746. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83747. defines.push("#define UV2");
  83748. }
  83749. }
  83750. //Logarithmic depth
  83751. if (material.useLogarithmicDepth) {
  83752. defines.push("#define LOGARITHMICDEPTH");
  83753. }
  83754. }
  83755. // Bones
  83756. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83757. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83758. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83759. if (mesh.numBoneInfluencers > 4) {
  83760. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83761. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83762. }
  83763. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83764. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83765. }
  83766. else {
  83767. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83768. }
  83769. // Instances
  83770. if (useInstances) {
  83771. defines.push("#define INSTANCES");
  83772. attribs.push("world0");
  83773. attribs.push("world1");
  83774. attribs.push("world2");
  83775. attribs.push("world3");
  83776. }
  83777. // Get correct effect
  83778. var join = defines.join("\n");
  83779. if (this._cachedDefines !== join) {
  83780. this._cachedDefines = join;
  83781. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83782. }
  83783. return this._effect.isReady();
  83784. };
  83785. return OutlineRenderer;
  83786. }());
  83787. BABYLON.OutlineRenderer = OutlineRenderer;
  83788. })(BABYLON || (BABYLON = {}));
  83789. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83790. var BABYLON;
  83791. (function (BABYLON) {
  83792. var FaceAdjacencies = /** @class */ (function () {
  83793. function FaceAdjacencies() {
  83794. this.edges = new Array();
  83795. this.edgesConnectedCount = 0;
  83796. }
  83797. return FaceAdjacencies;
  83798. }());
  83799. var EdgesRenderer = /** @class */ (function () {
  83800. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83801. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83802. if (epsilon === void 0) { epsilon = 0.95; }
  83803. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83804. this.edgesWidthScalerForOrthographic = 1000.0;
  83805. this.edgesWidthScalerForPerspective = 50.0;
  83806. this._linesPositions = new Array();
  83807. this._linesNormals = new Array();
  83808. this._linesIndices = new Array();
  83809. this._buffers = {};
  83810. this._checkVerticesInsteadOfIndices = false;
  83811. this._source = source;
  83812. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83813. this._epsilon = epsilon;
  83814. this._prepareRessources();
  83815. this._generateEdgesLines();
  83816. }
  83817. EdgesRenderer.prototype._prepareRessources = function () {
  83818. if (this._lineShader) {
  83819. return;
  83820. }
  83821. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83822. attributes: ["position", "normal"],
  83823. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83824. });
  83825. this._lineShader.disableDepthWrite = true;
  83826. this._lineShader.backFaceCulling = false;
  83827. };
  83828. EdgesRenderer.prototype._rebuild = function () {
  83829. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83830. if (buffer) {
  83831. buffer._rebuild();
  83832. }
  83833. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83834. if (buffer) {
  83835. buffer._rebuild();
  83836. }
  83837. var scene = this._source.getScene();
  83838. var engine = scene.getEngine();
  83839. this._ib = engine.createIndexBuffer(this._linesIndices);
  83840. };
  83841. EdgesRenderer.prototype.dispose = function () {
  83842. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83843. if (buffer) {
  83844. buffer.dispose();
  83845. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83846. }
  83847. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83848. if (buffer) {
  83849. buffer.dispose();
  83850. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83851. }
  83852. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83853. this._lineShader.dispose();
  83854. };
  83855. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83856. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83857. return 0;
  83858. }
  83859. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83860. return 1;
  83861. }
  83862. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83863. return 2;
  83864. }
  83865. return -1;
  83866. };
  83867. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83868. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83869. return 0;
  83870. }
  83871. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83872. return 1;
  83873. }
  83874. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83875. return 2;
  83876. }
  83877. return -1;
  83878. };
  83879. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83880. var needToCreateLine;
  83881. if (edge === undefined) {
  83882. needToCreateLine = true;
  83883. }
  83884. else {
  83885. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83886. needToCreateLine = dotProduct < this._epsilon;
  83887. }
  83888. if (needToCreateLine) {
  83889. var offset = this._linesPositions.length / 3;
  83890. var normal = p0.subtract(p1);
  83891. normal.normalize();
  83892. // Positions
  83893. this._linesPositions.push(p0.x);
  83894. this._linesPositions.push(p0.y);
  83895. this._linesPositions.push(p0.z);
  83896. this._linesPositions.push(p0.x);
  83897. this._linesPositions.push(p0.y);
  83898. this._linesPositions.push(p0.z);
  83899. this._linesPositions.push(p1.x);
  83900. this._linesPositions.push(p1.y);
  83901. this._linesPositions.push(p1.z);
  83902. this._linesPositions.push(p1.x);
  83903. this._linesPositions.push(p1.y);
  83904. this._linesPositions.push(p1.z);
  83905. // Normals
  83906. this._linesNormals.push(p1.x);
  83907. this._linesNormals.push(p1.y);
  83908. this._linesNormals.push(p1.z);
  83909. this._linesNormals.push(-1);
  83910. this._linesNormals.push(p1.x);
  83911. this._linesNormals.push(p1.y);
  83912. this._linesNormals.push(p1.z);
  83913. this._linesNormals.push(1);
  83914. this._linesNormals.push(p0.x);
  83915. this._linesNormals.push(p0.y);
  83916. this._linesNormals.push(p0.z);
  83917. this._linesNormals.push(-1);
  83918. this._linesNormals.push(p0.x);
  83919. this._linesNormals.push(p0.y);
  83920. this._linesNormals.push(p0.z);
  83921. this._linesNormals.push(1);
  83922. // Indices
  83923. this._linesIndices.push(offset);
  83924. this._linesIndices.push(offset + 1);
  83925. this._linesIndices.push(offset + 2);
  83926. this._linesIndices.push(offset);
  83927. this._linesIndices.push(offset + 2);
  83928. this._linesIndices.push(offset + 3);
  83929. }
  83930. };
  83931. EdgesRenderer.prototype._generateEdgesLines = function () {
  83932. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83933. var indices = this._source.getIndices();
  83934. if (!indices || !positions) {
  83935. return;
  83936. }
  83937. // First let's find adjacencies
  83938. var adjacencies = new Array();
  83939. var faceNormals = new Array();
  83940. var index;
  83941. var faceAdjacencies;
  83942. // Prepare faces
  83943. for (index = 0; index < indices.length; index += 3) {
  83944. faceAdjacencies = new FaceAdjacencies();
  83945. var p0Index = indices[index];
  83946. var p1Index = indices[index + 1];
  83947. var p2Index = indices[index + 2];
  83948. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83949. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83950. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83951. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83952. faceNormal.normalize();
  83953. faceNormals.push(faceNormal);
  83954. adjacencies.push(faceAdjacencies);
  83955. }
  83956. // Scan
  83957. for (index = 0; index < adjacencies.length; index++) {
  83958. faceAdjacencies = adjacencies[index];
  83959. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83960. var otherFaceAdjacencies = adjacencies[otherIndex];
  83961. if (faceAdjacencies.edgesConnectedCount === 3) {
  83962. break;
  83963. }
  83964. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83965. continue;
  83966. }
  83967. var otherP0 = indices[otherIndex * 3];
  83968. var otherP1 = indices[otherIndex * 3 + 1];
  83969. var otherP2 = indices[otherIndex * 3 + 2];
  83970. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83971. var otherEdgeIndex = 0;
  83972. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83973. continue;
  83974. }
  83975. switch (edgeIndex) {
  83976. case 0:
  83977. if (this._checkVerticesInsteadOfIndices) {
  83978. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83979. }
  83980. else {
  83981. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83982. }
  83983. break;
  83984. case 1:
  83985. if (this._checkVerticesInsteadOfIndices) {
  83986. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83987. }
  83988. else {
  83989. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83990. }
  83991. break;
  83992. case 2:
  83993. if (this._checkVerticesInsteadOfIndices) {
  83994. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83995. }
  83996. else {
  83997. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83998. }
  83999. break;
  84000. }
  84001. if (otherEdgeIndex === -1) {
  84002. continue;
  84003. }
  84004. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84005. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84006. faceAdjacencies.edgesConnectedCount++;
  84007. otherFaceAdjacencies.edgesConnectedCount++;
  84008. if (faceAdjacencies.edgesConnectedCount === 3) {
  84009. break;
  84010. }
  84011. }
  84012. }
  84013. }
  84014. // Create lines
  84015. for (index = 0; index < adjacencies.length; index++) {
  84016. // 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
  84017. var current = adjacencies[index];
  84018. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84019. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84020. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84021. }
  84022. // Merge into a single mesh
  84023. var engine = this._source.getScene().getEngine();
  84024. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84025. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84026. this._ib = engine.createIndexBuffer(this._linesIndices);
  84027. this._indicesCount = this._linesIndices.length;
  84028. };
  84029. EdgesRenderer.prototype.render = function () {
  84030. var scene = this._source.getScene();
  84031. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84032. return;
  84033. }
  84034. var engine = scene.getEngine();
  84035. this._lineShader._preBind();
  84036. // VBOs
  84037. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84038. scene.resetCachedMaterial();
  84039. this._lineShader.setColor4("color", this._source.edgesColor);
  84040. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84041. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84042. }
  84043. else {
  84044. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84045. }
  84046. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84047. this._lineShader.bind(this._source.getWorldMatrix());
  84048. // Draw order
  84049. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84050. this._lineShader.unbind();
  84051. engine.setDepthWrite(true);
  84052. };
  84053. return EdgesRenderer;
  84054. }());
  84055. BABYLON.EdgesRenderer = EdgesRenderer;
  84056. })(BABYLON || (BABYLON = {}));
  84057. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84058. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84059. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84060. s = arguments[i];
  84061. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84062. t[p] = s[p];
  84063. }
  84064. return t;
  84065. };
  84066. var BABYLON;
  84067. (function (BABYLON) {
  84068. /**
  84069. * The effect layer Helps adding post process effect blended with the main pass.
  84070. *
  84071. * This can be for instance use to generate glow or higlight effects on the scene.
  84072. *
  84073. * The effect layer class can not be used directly and is intented to inherited from to be
  84074. * customized per effects.
  84075. */
  84076. var EffectLayer = /** @class */ (function () {
  84077. /**
  84078. * Instantiates a new effect Layer and references it in the scene.
  84079. * @param name The name of the layer
  84080. * @param scene The scene to use the layer in
  84081. */
  84082. function EffectLayer(
  84083. /** The Friendly of the effect in the scene */
  84084. name, scene) {
  84085. this.name = name;
  84086. this._vertexBuffers = {};
  84087. this._maxSize = 0;
  84088. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84089. this._shouldRender = true;
  84090. this._postProcesses = [];
  84091. this._textures = [];
  84092. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84093. /**
  84094. * The clear color of the texture used to generate the glow map.
  84095. */
  84096. this.neutralColor = new BABYLON.Color4();
  84097. /**
  84098. * Specifies wether the highlight layer is enabled or not.
  84099. */
  84100. this.isEnabled = true;
  84101. /**
  84102. * An event triggered when the effect layer has been disposed.
  84103. */
  84104. this.onDisposeObservable = new BABYLON.Observable();
  84105. /**
  84106. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84107. */
  84108. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84109. /**
  84110. * An event triggered when the generated texture is being merged in the scene.
  84111. */
  84112. this.onBeforeComposeObservable = new BABYLON.Observable();
  84113. /**
  84114. * An event triggered when the generated texture has been merged in the scene.
  84115. */
  84116. this.onAfterComposeObservable = new BABYLON.Observable();
  84117. /**
  84118. * An event triggered when the efffect layer changes its size.
  84119. */
  84120. this.onSizeChangedObservable = new BABYLON.Observable();
  84121. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84122. this._engine = scene.getEngine();
  84123. this._maxSize = this._engine.getCaps().maxTextureSize;
  84124. this._scene.effectLayers.push(this);
  84125. // Generate Buffers
  84126. this._generateIndexBuffer();
  84127. this._genrateVertexBuffer();
  84128. }
  84129. Object.defineProperty(EffectLayer.prototype, "camera", {
  84130. /**
  84131. * Gets the camera attached to the layer.
  84132. */
  84133. get: function () {
  84134. return this._effectLayerOptions.camera;
  84135. },
  84136. enumerable: true,
  84137. configurable: true
  84138. });
  84139. /**
  84140. * Initializes the effect layer with the required options.
  84141. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84142. */
  84143. EffectLayer.prototype._init = function (options) {
  84144. // Adapt options
  84145. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84146. this._setMainTextureSize();
  84147. this._createMainTexture();
  84148. this._createTextureAndPostProcesses();
  84149. this._mergeEffect = this._createMergeEffect();
  84150. };
  84151. /**
  84152. * Generates the index buffer of the full screen quad blending to the main canvas.
  84153. */
  84154. EffectLayer.prototype._generateIndexBuffer = function () {
  84155. // Indices
  84156. var indices = [];
  84157. indices.push(0);
  84158. indices.push(1);
  84159. indices.push(2);
  84160. indices.push(0);
  84161. indices.push(2);
  84162. indices.push(3);
  84163. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84164. };
  84165. /**
  84166. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84167. */
  84168. EffectLayer.prototype._genrateVertexBuffer = function () {
  84169. // VBO
  84170. var vertices = [];
  84171. vertices.push(1, 1);
  84172. vertices.push(-1, 1);
  84173. vertices.push(-1, -1);
  84174. vertices.push(1, -1);
  84175. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84176. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84177. };
  84178. /**
  84179. * Sets the main texture desired size which is the closest power of two
  84180. * of the engine canvas size.
  84181. */
  84182. EffectLayer.prototype._setMainTextureSize = function () {
  84183. if (this._effectLayerOptions.mainTextureFixedSize) {
  84184. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84185. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84186. }
  84187. else {
  84188. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84189. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84190. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84191. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84192. }
  84193. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84194. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84195. };
  84196. /**
  84197. * Creates the main texture for the effect layer.
  84198. */
  84199. EffectLayer.prototype._createMainTexture = function () {
  84200. var _this = this;
  84201. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84202. width: this._mainTextureDesiredSize.width,
  84203. height: this._mainTextureDesiredSize.height
  84204. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84205. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84206. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84207. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84208. this._mainTexture.anisotropicFilteringLevel = 1;
  84209. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84210. this._mainTexture.renderParticles = false;
  84211. this._mainTexture.renderList = null;
  84212. this._mainTexture.ignoreCameraViewport = true;
  84213. // Custom render function
  84214. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84215. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84216. var index;
  84217. var engine = _this._scene.getEngine();
  84218. if (depthOnlySubMeshes.length) {
  84219. engine.setColorWrite(false);
  84220. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84221. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84222. }
  84223. engine.setColorWrite(true);
  84224. }
  84225. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84226. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84227. }
  84228. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84229. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84230. }
  84231. for (index = 0; index < transparentSubMeshes.length; index++) {
  84232. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84233. }
  84234. };
  84235. this._mainTexture.onClearObservable.add(function (engine) {
  84236. engine.clear(_this.neutralColor, true, true, true);
  84237. });
  84238. };
  84239. /**
  84240. * Checks for the readiness of the element composing the layer.
  84241. * @param subMesh the mesh to check for
  84242. * @param useInstances specify wether or not to use instances to render the mesh
  84243. * @param emissiveTexture the associated emissive texture used to generate the glow
  84244. * @return true if ready otherwise, false
  84245. */
  84246. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84247. var material = subMesh.getMaterial();
  84248. if (!material) {
  84249. return false;
  84250. }
  84251. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84252. return false;
  84253. }
  84254. var defines = [];
  84255. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84256. var mesh = subMesh.getMesh();
  84257. var uv1 = false;
  84258. var uv2 = false;
  84259. // Alpha test
  84260. if (material && material.needAlphaTesting()) {
  84261. var alphaTexture = material.getAlphaTestTexture();
  84262. if (alphaTexture) {
  84263. defines.push("#define ALPHATEST");
  84264. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84265. alphaTexture.coordinatesIndex === 1) {
  84266. defines.push("#define DIFFUSEUV2");
  84267. uv2 = true;
  84268. }
  84269. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84270. defines.push("#define DIFFUSEUV1");
  84271. uv1 = true;
  84272. }
  84273. }
  84274. }
  84275. // Emissive
  84276. if (emissiveTexture) {
  84277. defines.push("#define EMISSIVE");
  84278. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84279. emissiveTexture.coordinatesIndex === 1) {
  84280. defines.push("#define EMISSIVEUV2");
  84281. uv2 = true;
  84282. }
  84283. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84284. defines.push("#define EMISSIVEUV1");
  84285. uv1 = true;
  84286. }
  84287. }
  84288. if (uv1) {
  84289. attribs.push(BABYLON.VertexBuffer.UVKind);
  84290. defines.push("#define UV1");
  84291. }
  84292. if (uv2) {
  84293. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84294. defines.push("#define UV2");
  84295. }
  84296. // Bones
  84297. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84298. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84299. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84300. if (mesh.numBoneInfluencers > 4) {
  84301. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84302. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84303. }
  84304. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84305. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84306. }
  84307. else {
  84308. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84309. }
  84310. // Instances
  84311. if (useInstances) {
  84312. defines.push("#define INSTANCES");
  84313. attribs.push("world0");
  84314. attribs.push("world1");
  84315. attribs.push("world2");
  84316. attribs.push("world3");
  84317. }
  84318. // Get correct effect
  84319. var join = defines.join("\n");
  84320. if (this._cachedDefines !== join) {
  84321. this._cachedDefines = join;
  84322. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84323. }
  84324. return this._effectLayerMapGenerationEffect.isReady();
  84325. };
  84326. /**
  84327. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84328. */
  84329. EffectLayer.prototype.render = function () {
  84330. var currentEffect = this._mergeEffect;
  84331. // Check
  84332. if (!currentEffect.isReady())
  84333. return;
  84334. for (var i = 0; i < this._postProcesses.length; i++) {
  84335. if (!this._postProcesses[i].isReady()) {
  84336. return;
  84337. }
  84338. }
  84339. var engine = this._scene.getEngine();
  84340. this.onBeforeComposeObservable.notifyObservers(this);
  84341. // Render
  84342. engine.enableEffect(currentEffect);
  84343. engine.setState(false);
  84344. // VBOs
  84345. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84346. // Cache
  84347. var previousAlphaMode = engine.getAlphaMode();
  84348. // Go Blend.
  84349. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84350. // Blends the map on the main canvas.
  84351. this._internalRender(currentEffect);
  84352. // Restore Alpha
  84353. engine.setAlphaMode(previousAlphaMode);
  84354. this.onAfterComposeObservable.notifyObservers(this);
  84355. // Handle size changes.
  84356. var size = this._mainTexture.getSize();
  84357. this._setMainTextureSize();
  84358. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84359. // Recreate RTT and post processes on size change.
  84360. this.onSizeChangedObservable.notifyObservers(this);
  84361. this._disposeTextureAndPostProcesses();
  84362. this._createMainTexture();
  84363. this._createTextureAndPostProcesses();
  84364. }
  84365. };
  84366. /**
  84367. * Determine if a given mesh will be used in the current effect.
  84368. * @param mesh mesh to test
  84369. * @returns true if the mesh will be used
  84370. */
  84371. EffectLayer.prototype.hasMesh = function (mesh) {
  84372. return true;
  84373. };
  84374. /**
  84375. * Returns true if the layer contains information to display, otherwise false.
  84376. * @returns true if the glow layer should be rendered
  84377. */
  84378. EffectLayer.prototype.shouldRender = function () {
  84379. return this.isEnabled && this._shouldRender;
  84380. };
  84381. /**
  84382. * Returns true if the mesh should render, otherwise false.
  84383. * @param mesh The mesh to render
  84384. * @returns true if it should render otherwise false
  84385. */
  84386. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84387. return true;
  84388. };
  84389. /**
  84390. * Returns true if the mesh should render, otherwise false.
  84391. * @param mesh The mesh to render
  84392. * @returns true if it should render otherwise false
  84393. */
  84394. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84395. return true;
  84396. };
  84397. /**
  84398. * Renders the submesh passed in parameter to the generation map.
  84399. */
  84400. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84401. var _this = this;
  84402. if (!this.shouldRender()) {
  84403. return;
  84404. }
  84405. var material = subMesh.getMaterial();
  84406. var mesh = subMesh.getRenderingMesh();
  84407. var scene = this._scene;
  84408. var engine = scene.getEngine();
  84409. if (!material) {
  84410. return;
  84411. }
  84412. // Do not block in blend mode.
  84413. if (material.needAlphaBlendingForMesh(mesh)) {
  84414. return;
  84415. }
  84416. // Culling
  84417. engine.setState(material.backFaceCulling);
  84418. // Managing instances
  84419. var batch = mesh._getInstancesRenderList(subMesh._id);
  84420. if (batch.mustReturn) {
  84421. return;
  84422. }
  84423. // Early Exit per mesh
  84424. if (!this._shouldRenderMesh(mesh)) {
  84425. return;
  84426. }
  84427. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84428. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84429. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84430. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84431. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84432. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84433. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84434. // Alpha test
  84435. if (material && material.needAlphaTesting()) {
  84436. var alphaTexture = material.getAlphaTestTexture();
  84437. if (alphaTexture) {
  84438. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84439. var textureMatrix = alphaTexture.getTextureMatrix();
  84440. if (textureMatrix) {
  84441. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84442. }
  84443. }
  84444. }
  84445. // Glow emissive only
  84446. if (this._emissiveTextureAndColor.texture) {
  84447. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84448. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84449. }
  84450. // Bones
  84451. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84452. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84453. }
  84454. // Draw
  84455. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84456. }
  84457. else {
  84458. // Need to reset refresh rate of the shadowMap
  84459. this._mainTexture.resetRefreshCounter();
  84460. }
  84461. };
  84462. /**
  84463. * Rebuild the required buffers.
  84464. * @ignore Internal use only.
  84465. */
  84466. EffectLayer.prototype._rebuild = function () {
  84467. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84468. if (vb) {
  84469. vb._rebuild();
  84470. }
  84471. this._generateIndexBuffer();
  84472. };
  84473. /**
  84474. * Dispose only the render target textures and post process.
  84475. */
  84476. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84477. this._mainTexture.dispose();
  84478. for (var i = 0; i < this._postProcesses.length; i++) {
  84479. if (this._postProcesses[i]) {
  84480. this._postProcesses[i].dispose();
  84481. }
  84482. }
  84483. this._postProcesses = [];
  84484. for (var i = 0; i < this._textures.length; i++) {
  84485. if (this._textures[i]) {
  84486. this._textures[i].dispose();
  84487. }
  84488. }
  84489. this._textures = [];
  84490. };
  84491. /**
  84492. * Dispose the highlight layer and free resources.
  84493. */
  84494. EffectLayer.prototype.dispose = function () {
  84495. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84496. if (vertexBuffer) {
  84497. vertexBuffer.dispose();
  84498. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84499. }
  84500. if (this._indexBuffer) {
  84501. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84502. this._indexBuffer = null;
  84503. }
  84504. // Clean textures and post processes
  84505. this._disposeTextureAndPostProcesses();
  84506. // Remove from scene
  84507. var index = this._scene.effectLayers.indexOf(this, 0);
  84508. if (index > -1) {
  84509. this._scene.effectLayers.splice(index, 1);
  84510. }
  84511. // Callback
  84512. this.onDisposeObservable.notifyObservers(this);
  84513. this.onDisposeObservable.clear();
  84514. this.onBeforeRenderMainTextureObservable.clear();
  84515. this.onBeforeComposeObservable.clear();
  84516. this.onAfterComposeObservable.clear();
  84517. this.onSizeChangedObservable.clear();
  84518. };
  84519. return EffectLayer;
  84520. }());
  84521. BABYLON.EffectLayer = EffectLayer;
  84522. })(BABYLON || (BABYLON = {}));
  84523. //# sourceMappingURL=babylon.effectLayer.js.map
  84524. var BABYLON;
  84525. (function (BABYLON) {
  84526. /**
  84527. * Special Glow Blur post process only blurring the alpha channel
  84528. * It enforces keeping the most luminous color in the color channel.
  84529. */
  84530. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84531. __extends(GlowBlurPostProcess, _super);
  84532. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84534. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84535. _this.direction = direction;
  84536. _this.kernel = kernel;
  84537. _this.onApplyObservable.add(function (effect) {
  84538. effect.setFloat2("screenSize", _this.width, _this.height);
  84539. effect.setVector2("direction", _this.direction);
  84540. effect.setFloat("blurWidth", _this.kernel);
  84541. });
  84542. return _this;
  84543. }
  84544. return GlowBlurPostProcess;
  84545. }(BABYLON.PostProcess));
  84546. /**
  84547. * The highlight layer Helps adding a glow effect around a mesh.
  84548. *
  84549. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84550. * glowy meshes to your scene.
  84551. *
  84552. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84553. */
  84554. var HighlightLayer = /** @class */ (function (_super) {
  84555. __extends(HighlightLayer, _super);
  84556. /**
  84557. * Instantiates a new highlight Layer and references it to the scene..
  84558. * @param name The name of the layer
  84559. * @param scene The scene to use the layer in
  84560. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84561. */
  84562. function HighlightLayer(name, scene, options) {
  84563. var _this = _super.call(this, name, scene) || this;
  84564. _this.name = name;
  84565. /**
  84566. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84567. */
  84568. _this.innerGlow = true;
  84569. /**
  84570. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84571. */
  84572. _this.outerGlow = true;
  84573. /**
  84574. * An event triggered when the highlight layer is being blurred.
  84575. */
  84576. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84577. /**
  84578. * An event triggered when the highlight layer has been blurred.
  84579. */
  84580. _this.onAfterBlurObservable = new BABYLON.Observable();
  84581. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84582. _this._meshes = {};
  84583. _this._excludedMeshes = {};
  84584. _this.neutralColor = HighlightLayer.NeutralColor;
  84585. // Warn on stencil
  84586. if (!_this._engine.isStencilEnable) {
  84587. 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 }");
  84588. }
  84589. // Adapt options
  84590. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84591. // Initialize the layer
  84592. _this._init({
  84593. alphaBlendingMode: _this._options.alphaBlendingMode,
  84594. camera: _this._options.camera,
  84595. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84596. mainTextureRatio: _this._options.mainTextureRatio
  84597. });
  84598. // Do not render as long as no meshes have been added
  84599. _this._shouldRender = false;
  84600. return _this;
  84601. }
  84602. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84603. /**
  84604. * Gets the horizontal size of the blur.
  84605. */
  84606. get: function () {
  84607. return this._horizontalBlurPostprocess.kernel;
  84608. },
  84609. /**
  84610. * Specifies the horizontal size of the blur.
  84611. */
  84612. set: function (value) {
  84613. this._horizontalBlurPostprocess.kernel = value;
  84614. },
  84615. enumerable: true,
  84616. configurable: true
  84617. });
  84618. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84619. /**
  84620. * Gets the vertical size of the blur.
  84621. */
  84622. get: function () {
  84623. return this._verticalBlurPostprocess.kernel;
  84624. },
  84625. /**
  84626. * Specifies the vertical size of the blur.
  84627. */
  84628. set: function (value) {
  84629. this._verticalBlurPostprocess.kernel = value;
  84630. },
  84631. enumerable: true,
  84632. configurable: true
  84633. });
  84634. /**
  84635. * Get the effect name of the layer.
  84636. * @return The effect name
  84637. */
  84638. HighlightLayer.prototype.getEffectName = function () {
  84639. return HighlightLayer.EffectName;
  84640. };
  84641. /**
  84642. * Create the merge effect. This is the shader use to blit the information back
  84643. * to the main canvas at the end of the scene rendering.
  84644. */
  84645. HighlightLayer.prototype._createMergeEffect = function () {
  84646. // Effect
  84647. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84648. };
  84649. /**
  84650. * Creates the render target textures and post processes used in the highlight layer.
  84651. */
  84652. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84653. var _this = this;
  84654. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84655. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84656. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84657. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84658. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84659. width: blurTextureWidth,
  84660. height: blurTextureHeight
  84661. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84662. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84663. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84664. this._blurTexture.anisotropicFilteringLevel = 16;
  84665. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84666. this._blurTexture.renderParticles = false;
  84667. this._blurTexture.ignoreCameraViewport = true;
  84668. this._textures = [this._blurTexture];
  84669. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84670. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84671. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84672. effect.setTexture("textureSampler", _this._mainTexture);
  84673. });
  84674. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84675. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84676. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84677. });
  84678. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84679. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84680. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84681. });
  84682. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84683. }
  84684. else {
  84685. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84686. width: blurTextureWidth,
  84687. height: blurTextureHeight
  84688. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84689. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84690. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84691. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84692. effect.setTexture("textureSampler", _this._mainTexture);
  84693. });
  84694. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84695. width: blurTextureWidth,
  84696. height: blurTextureHeight
  84697. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84698. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84699. }
  84700. this._mainTexture.onAfterUnbindObservable.add(function () {
  84701. _this.onBeforeBlurObservable.notifyObservers(_this);
  84702. var internalTexture = _this._blurTexture.getInternalTexture();
  84703. if (internalTexture) {
  84704. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84705. }
  84706. _this.onAfterBlurObservable.notifyObservers(_this);
  84707. });
  84708. // Prevent autoClear.
  84709. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84710. };
  84711. /**
  84712. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84713. */
  84714. HighlightLayer.prototype.needStencil = function () {
  84715. return true;
  84716. };
  84717. /**
  84718. * Checks for the readiness of the element composing the layer.
  84719. * @param subMesh the mesh to check for
  84720. * @param useInstances specify wether or not to use instances to render the mesh
  84721. * @param emissiveTexture the associated emissive texture used to generate the glow
  84722. * @return true if ready otherwise, false
  84723. */
  84724. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84725. var material = subMesh.getMaterial();
  84726. var mesh = subMesh.getRenderingMesh();
  84727. if (!material || !mesh || !this._meshes) {
  84728. return false;
  84729. }
  84730. var emissiveTexture = null;
  84731. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84732. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84733. emissiveTexture = material.emissiveTexture;
  84734. }
  84735. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84736. };
  84737. /**
  84738. * Implementation specific of rendering the generating effect on the main canvas.
  84739. * @param effect The effect used to render through
  84740. */
  84741. HighlightLayer.prototype._internalRender = function (effect) {
  84742. // Texture
  84743. effect.setTexture("textureSampler", this._blurTexture);
  84744. // Cache
  84745. var engine = this._engine;
  84746. var previousStencilBuffer = engine.getStencilBuffer();
  84747. var previousStencilFunction = engine.getStencilFunction();
  84748. var previousStencilMask = engine.getStencilMask();
  84749. var previousStencilOperationPass = engine.getStencilOperationPass();
  84750. var previousStencilOperationFail = engine.getStencilOperationFail();
  84751. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84752. var previousStencilReference = engine.getStencilFunctionReference();
  84753. // Stencil operations
  84754. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84755. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84756. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84757. // Draw order
  84758. engine.setStencilMask(0x00);
  84759. engine.setStencilBuffer(true);
  84760. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84761. // 2 passes inner outer
  84762. if (this.outerGlow) {
  84763. effect.setFloat("offset", 0);
  84764. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84765. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84766. }
  84767. if (this.innerGlow) {
  84768. effect.setFloat("offset", 1);
  84769. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84770. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84771. }
  84772. // Restore Cache
  84773. engine.setStencilFunction(previousStencilFunction);
  84774. engine.setStencilMask(previousStencilMask);
  84775. engine.setStencilBuffer(previousStencilBuffer);
  84776. engine.setStencilOperationPass(previousStencilOperationPass);
  84777. engine.setStencilOperationFail(previousStencilOperationFail);
  84778. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84779. engine.setStencilFunctionReference(previousStencilReference);
  84780. };
  84781. /**
  84782. * Returns true if the layer contains information to display, otherwise false.
  84783. */
  84784. HighlightLayer.prototype.shouldRender = function () {
  84785. if (_super.prototype.shouldRender.call(this)) {
  84786. return this._meshes ? true : false;
  84787. }
  84788. return false;
  84789. };
  84790. /**
  84791. * Returns true if the mesh should render, otherwise false.
  84792. * @param mesh The mesh to render
  84793. * @returns true if it should render otherwise false
  84794. */
  84795. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84796. // Excluded Mesh
  84797. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84798. return false;
  84799. }
  84800. ;
  84801. return true;
  84802. };
  84803. /**
  84804. * Sets the required values for both the emissive texture and and the main color.
  84805. */
  84806. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84807. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84808. if (highlightLayerMesh) {
  84809. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84810. }
  84811. else {
  84812. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84813. }
  84814. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84815. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84816. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84817. }
  84818. else {
  84819. this._emissiveTextureAndColor.texture = null;
  84820. }
  84821. };
  84822. /**
  84823. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84824. * @param mesh The mesh to exclude from the highlight layer
  84825. */
  84826. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84827. if (!this._excludedMeshes) {
  84828. return;
  84829. }
  84830. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84831. if (!meshExcluded) {
  84832. this._excludedMeshes[mesh.uniqueId] = {
  84833. mesh: mesh,
  84834. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84835. mesh.getEngine().setStencilBuffer(false);
  84836. }),
  84837. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84838. mesh.getEngine().setStencilBuffer(true);
  84839. }),
  84840. };
  84841. }
  84842. };
  84843. /**
  84844. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84845. * @param mesh The mesh to highlight
  84846. */
  84847. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84848. if (!this._excludedMeshes) {
  84849. return;
  84850. }
  84851. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84852. if (meshExcluded) {
  84853. if (meshExcluded.beforeRender) {
  84854. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84855. }
  84856. if (meshExcluded.afterRender) {
  84857. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84858. }
  84859. }
  84860. this._excludedMeshes[mesh.uniqueId] = null;
  84861. };
  84862. /**
  84863. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84864. * @param mesh mesh to test
  84865. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84866. */
  84867. HighlightLayer.prototype.hasMesh = function (mesh) {
  84868. if (!this._meshes) {
  84869. return false;
  84870. }
  84871. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84872. };
  84873. /**
  84874. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84875. * @param mesh The mesh to highlight
  84876. * @param color The color of the highlight
  84877. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84878. */
  84879. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84880. var _this = this;
  84881. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84882. if (!this._meshes) {
  84883. return;
  84884. }
  84885. var meshHighlight = this._meshes[mesh.uniqueId];
  84886. if (meshHighlight) {
  84887. meshHighlight.color = color;
  84888. }
  84889. else {
  84890. this._meshes[mesh.uniqueId] = {
  84891. mesh: mesh,
  84892. color: color,
  84893. // Lambda required for capture due to Observable this context
  84894. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84895. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84896. _this._defaultStencilReference(mesh);
  84897. }
  84898. else {
  84899. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84900. }
  84901. }),
  84902. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84903. glowEmissiveOnly: glowEmissiveOnly
  84904. };
  84905. }
  84906. this._shouldRender = true;
  84907. };
  84908. /**
  84909. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84910. * @param mesh The mesh to highlight
  84911. */
  84912. HighlightLayer.prototype.removeMesh = function (mesh) {
  84913. if (!this._meshes) {
  84914. return;
  84915. }
  84916. var meshHighlight = this._meshes[mesh.uniqueId];
  84917. if (meshHighlight) {
  84918. if (meshHighlight.observerHighlight) {
  84919. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84920. }
  84921. if (meshHighlight.observerDefault) {
  84922. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84923. }
  84924. delete this._meshes[mesh.uniqueId];
  84925. }
  84926. this._shouldRender = false;
  84927. for (var meshHighlightToCheck in this._meshes) {
  84928. if (this._meshes[meshHighlightToCheck]) {
  84929. this._shouldRender = true;
  84930. break;
  84931. }
  84932. }
  84933. };
  84934. /**
  84935. * Force the stencil to the normal expected value for none glowing parts
  84936. */
  84937. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84938. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84939. };
  84940. /**
  84941. * Free any resources and references associated to a mesh.
  84942. * Internal use
  84943. * @param mesh The mesh to free.
  84944. */
  84945. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84946. this.removeMesh(mesh);
  84947. this.removeExcludedMesh(mesh);
  84948. };
  84949. /**
  84950. * Dispose the highlight layer and free resources.
  84951. */
  84952. HighlightLayer.prototype.dispose = function () {
  84953. if (this._meshes) {
  84954. // Clean mesh references
  84955. for (var id in this._meshes) {
  84956. var meshHighlight = this._meshes[id];
  84957. if (meshHighlight && meshHighlight.mesh) {
  84958. if (meshHighlight.observerHighlight) {
  84959. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84960. }
  84961. if (meshHighlight.observerDefault) {
  84962. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84963. }
  84964. }
  84965. }
  84966. this._meshes = null;
  84967. }
  84968. if (this._excludedMeshes) {
  84969. for (var id in this._excludedMeshes) {
  84970. var meshHighlight = this._excludedMeshes[id];
  84971. if (meshHighlight) {
  84972. if (meshHighlight.beforeRender) {
  84973. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84974. }
  84975. if (meshHighlight.afterRender) {
  84976. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84977. }
  84978. }
  84979. }
  84980. this._excludedMeshes = null;
  84981. }
  84982. _super.prototype.dispose.call(this);
  84983. };
  84984. /**
  84985. * Effect Name of the highlight layer.
  84986. */
  84987. HighlightLayer.EffectName = "HighlightLayer";
  84988. /**
  84989. * The neutral color used during the preparation of the glow effect.
  84990. * This is black by default as the blend operation is a blend operation.
  84991. */
  84992. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84993. /**
  84994. * Stencil value used for glowing meshes.
  84995. */
  84996. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84997. /**
  84998. * Stencil value used for the other meshes in the scene.
  84999. */
  85000. HighlightLayer.NormalMeshStencilReference = 0x01;
  85001. return HighlightLayer;
  85002. }(BABYLON.EffectLayer));
  85003. BABYLON.HighlightLayer = HighlightLayer;
  85004. })(BABYLON || (BABYLON = {}));
  85005. //# sourceMappingURL=babylon.highlightLayer.js.map
  85006. var BABYLON;
  85007. (function (BABYLON) {
  85008. /**
  85009. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85010. *
  85011. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85012. * glowy meshes to your scene.
  85013. *
  85014. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85015. */
  85016. var GlowLayer = /** @class */ (function (_super) {
  85017. __extends(GlowLayer, _super);
  85018. /**
  85019. * Instantiates a new glow Layer and references it to the scene.
  85020. * @param name The name of the layer
  85021. * @param scene The scene to use the layer in
  85022. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85023. */
  85024. function GlowLayer(name, scene, options) {
  85025. var _this = _super.call(this, name, scene) || this;
  85026. _this.name = name;
  85027. _this._intensity = 1.0;
  85028. _this._includedOnlyMeshes = [];
  85029. _this._excludedMeshes = [];
  85030. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85031. // Adapt options
  85032. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85033. // Initialize the layer
  85034. _this._init({
  85035. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85036. camera: _this._options.camera,
  85037. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85038. mainTextureRatio: _this._options.mainTextureRatio
  85039. });
  85040. return _this;
  85041. }
  85042. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85043. /**
  85044. * Gets the kernel size of the blur.
  85045. */
  85046. get: function () {
  85047. return this._horizontalBlurPostprocess1.kernel;
  85048. },
  85049. /**
  85050. * Sets the kernel size of the blur.
  85051. */
  85052. set: function (value) {
  85053. this._horizontalBlurPostprocess1.kernel = value;
  85054. this._verticalBlurPostprocess1.kernel = value;
  85055. this._horizontalBlurPostprocess2.kernel = value;
  85056. this._verticalBlurPostprocess2.kernel = value;
  85057. },
  85058. enumerable: true,
  85059. configurable: true
  85060. });
  85061. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85062. /**
  85063. * Gets the glow intensity.
  85064. */
  85065. get: function () {
  85066. return this._intensity;
  85067. },
  85068. /**
  85069. * Sets the glow intensity.
  85070. */
  85071. set: function (value) {
  85072. this._intensity = value;
  85073. },
  85074. enumerable: true,
  85075. configurable: true
  85076. });
  85077. /**
  85078. * Get the effect name of the layer.
  85079. * @return The effect name
  85080. */
  85081. GlowLayer.prototype.getEffectName = function () {
  85082. return GlowLayer.EffectName;
  85083. };
  85084. /**
  85085. * Create the merge effect. This is the shader use to blit the information back
  85086. * to the main canvas at the end of the scene rendering.
  85087. */
  85088. GlowLayer.prototype._createMergeEffect = function () {
  85089. // Effect
  85090. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85091. };
  85092. /**
  85093. * Creates the render target textures and post processes used in the glow layer.
  85094. */
  85095. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85096. var _this = this;
  85097. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85098. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85099. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85100. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85101. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85102. width: blurTextureWidth,
  85103. height: blurTextureHeight
  85104. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85105. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85106. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85107. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85108. this._blurTexture1.renderParticles = false;
  85109. this._blurTexture1.ignoreCameraViewport = true;
  85110. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85111. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85112. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85113. width: blurTextureWidth2,
  85114. height: blurTextureHeight2
  85115. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85116. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85117. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85118. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85119. this._blurTexture2.renderParticles = false;
  85120. this._blurTexture2.ignoreCameraViewport = true;
  85121. this._textures = [this._blurTexture1, this._blurTexture2];
  85122. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85123. width: blurTextureWidth,
  85124. height: blurTextureHeight
  85125. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85126. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85127. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85128. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85129. effect.setTexture("textureSampler", _this._mainTexture);
  85130. });
  85131. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85132. width: blurTextureWidth,
  85133. height: blurTextureHeight
  85134. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85135. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85136. width: blurTextureWidth2,
  85137. height: blurTextureHeight2
  85138. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85139. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85140. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85141. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85142. effect.setTexture("textureSampler", _this._blurTexture1);
  85143. });
  85144. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85145. width: blurTextureWidth2,
  85146. height: blurTextureHeight2
  85147. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85148. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85149. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85150. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85151. this._mainTexture.samples = this._options.mainTextureSamples;
  85152. this._mainTexture.onAfterUnbindObservable.add(function () {
  85153. var internalTexture = _this._blurTexture1.getInternalTexture();
  85154. if (internalTexture) {
  85155. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85156. internalTexture = _this._blurTexture2.getInternalTexture();
  85157. if (internalTexture) {
  85158. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85159. }
  85160. }
  85161. });
  85162. // Prevent autoClear.
  85163. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85164. };
  85165. /**
  85166. * Checks for the readiness of the element composing the layer.
  85167. * @param subMesh the mesh to check for
  85168. * @param useInstances specify wether or not to use instances to render the mesh
  85169. * @param emissiveTexture the associated emissive texture used to generate the glow
  85170. * @return true if ready otherwise, false
  85171. */
  85172. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85173. var material = subMesh.getMaterial();
  85174. var mesh = subMesh.getRenderingMesh();
  85175. if (!material || !mesh) {
  85176. return false;
  85177. }
  85178. var emissiveTexture = material.emissiveTexture;
  85179. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85180. };
  85181. /**
  85182. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85183. */
  85184. GlowLayer.prototype.needStencil = function () {
  85185. return false;
  85186. };
  85187. /**
  85188. * Implementation specific of rendering the generating effect on the main canvas.
  85189. * @param effect The effect used to render through
  85190. */
  85191. GlowLayer.prototype._internalRender = function (effect) {
  85192. // Texture
  85193. effect.setTexture("textureSampler", this._blurTexture1);
  85194. effect.setTexture("textureSampler2", this._blurTexture2);
  85195. effect.setFloat("offset", this._intensity);
  85196. // Cache
  85197. var engine = this._engine;
  85198. var previousStencilBuffer = engine.getStencilBuffer();
  85199. // Draw order
  85200. engine.setStencilBuffer(false);
  85201. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85202. // Draw order
  85203. engine.setStencilBuffer(previousStencilBuffer);
  85204. };
  85205. /**
  85206. * Sets the required values for both the emissive texture and and the main color.
  85207. */
  85208. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85209. var textureLevel = 1.0;
  85210. if (this.customEmissiveTextureSelector) {
  85211. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85212. }
  85213. else {
  85214. if (material) {
  85215. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85216. if (this._emissiveTextureAndColor.texture) {
  85217. textureLevel = this._emissiveTextureAndColor.texture.level;
  85218. }
  85219. }
  85220. else {
  85221. this._emissiveTextureAndColor.texture = null;
  85222. }
  85223. }
  85224. if (this.customEmissiveColorSelector) {
  85225. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85226. }
  85227. else {
  85228. if (material.emissiveColor) {
  85229. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85230. }
  85231. else {
  85232. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85233. }
  85234. }
  85235. };
  85236. /**
  85237. * Returns true if the mesh should render, otherwise false.
  85238. * @param mesh The mesh to render
  85239. * @returns true if it should render otherwise false
  85240. */
  85241. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85242. return this.hasMesh(mesh);
  85243. };
  85244. /**
  85245. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85246. * @param mesh The mesh to exclude from the glow layer
  85247. */
  85248. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85249. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85250. this._excludedMeshes.push(mesh.uniqueId);
  85251. }
  85252. };
  85253. /**
  85254. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85255. * @param mesh The mesh to remove
  85256. */
  85257. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85258. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85259. if (index !== -1) {
  85260. this._excludedMeshes.splice(index, 1);
  85261. }
  85262. };
  85263. /**
  85264. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85265. * @param mesh The mesh to include in the glow layer
  85266. */
  85267. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85268. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85269. this._includedOnlyMeshes.push(mesh.uniqueId);
  85270. }
  85271. };
  85272. /**
  85273. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85274. * @param mesh The mesh to remove
  85275. */
  85276. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85277. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85278. if (index !== -1) {
  85279. this._includedOnlyMeshes.splice(index, 1);
  85280. }
  85281. };
  85282. /**
  85283. * Determine if a given mesh will be used in the glow layer
  85284. * @param mesh The mesh to test
  85285. * @returns true if the mesh will be highlighted by the current glow layer
  85286. */
  85287. GlowLayer.prototype.hasMesh = function (mesh) {
  85288. // Included Mesh
  85289. if (this._includedOnlyMeshes.length) {
  85290. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85291. }
  85292. ;
  85293. // Excluded Mesh
  85294. if (this._excludedMeshes.length) {
  85295. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85296. }
  85297. ;
  85298. return true;
  85299. };
  85300. /**
  85301. * Free any resources and references associated to a mesh.
  85302. * Internal use
  85303. * @param mesh The mesh to free.
  85304. */
  85305. GlowLayer.prototype._disposeMesh = function (mesh) {
  85306. this.removeIncludedOnlyMesh(mesh);
  85307. this.removeExcludedMesh(mesh);
  85308. };
  85309. /**
  85310. * Effect Name of the layer.
  85311. */
  85312. GlowLayer.EffectName = "GlowLayer";
  85313. /**
  85314. * The default blur kernel size used for the glow.
  85315. */
  85316. GlowLayer.DefaultBlurKernelSize = 32;
  85317. /**
  85318. * The default texture size ratio used for the glow.
  85319. */
  85320. GlowLayer.DefaultTextureRatio = 0.5;
  85321. return GlowLayer;
  85322. }(BABYLON.EffectLayer));
  85323. BABYLON.GlowLayer = GlowLayer;
  85324. })(BABYLON || (BABYLON = {}));
  85325. //# sourceMappingURL=babylon.glowLayer.js.map
  85326. var BABYLON;
  85327. (function (BABYLON) {
  85328. /**
  85329. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85330. */
  85331. var AssetTaskState;
  85332. (function (AssetTaskState) {
  85333. /**
  85334. * Initialization
  85335. */
  85336. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85337. /**
  85338. * Running
  85339. */
  85340. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85341. /**
  85342. * Done
  85343. */
  85344. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85345. /**
  85346. * Error
  85347. */
  85348. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85349. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85350. /**
  85351. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85352. */
  85353. var AbstractAssetTask = /** @class */ (function () {
  85354. /**
  85355. * Creates a new {BABYLON.AssetsManager}
  85356. * @param name defines the name of the task
  85357. */
  85358. function AbstractAssetTask(
  85359. /**
  85360. * Task name
  85361. */ name) {
  85362. this.name = name;
  85363. this._isCompleted = false;
  85364. this._taskState = AssetTaskState.INIT;
  85365. }
  85366. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85367. /**
  85368. * Get if the task is completed
  85369. */
  85370. get: function () {
  85371. return this._isCompleted;
  85372. },
  85373. enumerable: true,
  85374. configurable: true
  85375. });
  85376. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85377. /**
  85378. * Gets the current state of the task
  85379. */
  85380. get: function () {
  85381. return this._taskState;
  85382. },
  85383. enumerable: true,
  85384. configurable: true
  85385. });
  85386. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85387. /**
  85388. * Gets the current error object (if task is in error)
  85389. */
  85390. get: function () {
  85391. return this._errorObject;
  85392. },
  85393. enumerable: true,
  85394. configurable: true
  85395. });
  85396. /**
  85397. * Internal only
  85398. * @ignore
  85399. */
  85400. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85401. if (this._errorObject) {
  85402. return;
  85403. }
  85404. this._errorObject = {
  85405. message: message,
  85406. exception: exception
  85407. };
  85408. };
  85409. /**
  85410. * Execute the current task
  85411. * @param scene defines the scene where you want your assets to be loaded
  85412. * @param onSuccess is a callback called when the task is successfully executed
  85413. * @param onError is a callback called if an error occurs
  85414. */
  85415. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85416. var _this = this;
  85417. this._taskState = AssetTaskState.RUNNING;
  85418. this.runTask(scene, function () {
  85419. _this.onDoneCallback(onSuccess, onError);
  85420. }, function (msg, exception) {
  85421. _this.onErrorCallback(onError, msg, exception);
  85422. });
  85423. };
  85424. /**
  85425. * Execute the current task
  85426. * @param scene defines the scene where you want your assets to be loaded
  85427. * @param onSuccess is a callback called when the task is successfully executed
  85428. * @param onError is a callback called if an error occurs
  85429. */
  85430. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85431. throw new Error("runTask is not implemented");
  85432. };
  85433. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85434. this._taskState = AssetTaskState.ERROR;
  85435. this._errorObject = {
  85436. message: message,
  85437. exception: exception
  85438. };
  85439. if (this.onError) {
  85440. this.onError(this, message, exception);
  85441. }
  85442. onError();
  85443. };
  85444. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85445. try {
  85446. this._taskState = AssetTaskState.DONE;
  85447. this._isCompleted = true;
  85448. if (this.onSuccess) {
  85449. this.onSuccess(this);
  85450. }
  85451. onSuccess();
  85452. }
  85453. catch (e) {
  85454. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85455. }
  85456. };
  85457. return AbstractAssetTask;
  85458. }());
  85459. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85460. /**
  85461. * Class used to share progress information about assets loading
  85462. */
  85463. var AssetsProgressEvent = /** @class */ (function () {
  85464. /**
  85465. * Creates a {BABYLON.AssetsProgressEvent}
  85466. * @param remainingCount defines the number of remaining tasks to process
  85467. * @param totalCount defines the total number of tasks
  85468. * @param task defines the task that was just processed
  85469. */
  85470. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85471. this.remainingCount = remainingCount;
  85472. this.totalCount = totalCount;
  85473. this.task = task;
  85474. }
  85475. return AssetsProgressEvent;
  85476. }());
  85477. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85478. /**
  85479. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85480. */
  85481. var MeshAssetTask = /** @class */ (function (_super) {
  85482. __extends(MeshAssetTask, _super);
  85483. /**
  85484. * Creates a new {BABYLON.MeshAssetTask}
  85485. * @param name defines the name of the task
  85486. * @param meshesNames defines the list of mesh's names you want to load
  85487. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85488. * @param sceneFilename defines the filename of the scene to load from
  85489. */
  85490. function MeshAssetTask(
  85491. /**
  85492. * Defines the name of the task
  85493. */
  85494. name,
  85495. /**
  85496. * Defines the list of mesh's names you want to load
  85497. */
  85498. meshesNames,
  85499. /**
  85500. * Defines the root url to use as a base to load your meshes and associated resources
  85501. */
  85502. rootUrl,
  85503. /**
  85504. * Defines the filename of the scene to load from
  85505. */
  85506. sceneFilename) {
  85507. var _this = _super.call(this, name) || this;
  85508. _this.name = name;
  85509. _this.meshesNames = meshesNames;
  85510. _this.rootUrl = rootUrl;
  85511. _this.sceneFilename = sceneFilename;
  85512. return _this;
  85513. }
  85514. /**
  85515. * Execute the current task
  85516. * @param scene defines the scene where you want your assets to be loaded
  85517. * @param onSuccess is a callback called when the task is successfully executed
  85518. * @param onError is a callback called if an error occurs
  85519. */
  85520. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85521. var _this = this;
  85522. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85523. _this.loadedMeshes = meshes;
  85524. _this.loadedParticleSystems = particleSystems;
  85525. _this.loadedSkeletons = skeletons;
  85526. onSuccess();
  85527. }, null, function (scene, message, exception) {
  85528. onError(message, exception);
  85529. });
  85530. };
  85531. return MeshAssetTask;
  85532. }(AbstractAssetTask));
  85533. BABYLON.MeshAssetTask = MeshAssetTask;
  85534. /**
  85535. * Define a task used by {BABYLON.AssetsManager} to load text content
  85536. */
  85537. var TextFileAssetTask = /** @class */ (function (_super) {
  85538. __extends(TextFileAssetTask, _super);
  85539. /**
  85540. * Creates a new TextFileAssetTask object
  85541. * @param name defines the name of the task
  85542. * @param url defines the location of the file to load
  85543. */
  85544. function TextFileAssetTask(
  85545. /**
  85546. * Defines the name of the task
  85547. */
  85548. name,
  85549. /**
  85550. * Defines the location of the file to load
  85551. */
  85552. url) {
  85553. var _this = _super.call(this, name) || this;
  85554. _this.name = name;
  85555. _this.url = url;
  85556. return _this;
  85557. }
  85558. /**
  85559. * Execute the current task
  85560. * @param scene defines the scene where you want your assets to be loaded
  85561. * @param onSuccess is a callback called when the task is successfully executed
  85562. * @param onError is a callback called if an error occurs
  85563. */
  85564. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85565. var _this = this;
  85566. scene._loadFile(this.url, function (data) {
  85567. _this.text = data;
  85568. onSuccess();
  85569. }, undefined, false, false, function (request, exception) {
  85570. if (request) {
  85571. onError(request.status + " " + request.statusText, exception);
  85572. }
  85573. });
  85574. };
  85575. return TextFileAssetTask;
  85576. }(AbstractAssetTask));
  85577. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85578. /**
  85579. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85580. */
  85581. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85582. __extends(BinaryFileAssetTask, _super);
  85583. /**
  85584. * Creates a new BinaryFileAssetTask object
  85585. * @param name defines the name of the new task
  85586. * @param url defines the location of the file to load
  85587. */
  85588. function BinaryFileAssetTask(
  85589. /**
  85590. * Defines the name of the task
  85591. */
  85592. name,
  85593. /**
  85594. * Defines the location of the file to load
  85595. */
  85596. url) {
  85597. var _this = _super.call(this, name) || this;
  85598. _this.name = name;
  85599. _this.url = url;
  85600. return _this;
  85601. }
  85602. /**
  85603. * Execute the current task
  85604. * @param scene defines the scene where you want your assets to be loaded
  85605. * @param onSuccess is a callback called when the task is successfully executed
  85606. * @param onError is a callback called if an error occurs
  85607. */
  85608. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85609. var _this = this;
  85610. scene._loadFile(this.url, function (data) {
  85611. _this.data = data;
  85612. onSuccess();
  85613. }, undefined, true, true, function (request, exception) {
  85614. if (request) {
  85615. onError(request.status + " " + request.statusText, exception);
  85616. }
  85617. });
  85618. };
  85619. return BinaryFileAssetTask;
  85620. }(AbstractAssetTask));
  85621. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85622. /**
  85623. * Define a task used by {BABYLON.AssetsManager} to load images
  85624. */
  85625. var ImageAssetTask = /** @class */ (function (_super) {
  85626. __extends(ImageAssetTask, _super);
  85627. /**
  85628. * Creates a new ImageAssetTask
  85629. * @param name defines the name of the task
  85630. * @param url defines the location of the image to load
  85631. */
  85632. function ImageAssetTask(
  85633. /**
  85634. * Defines the name of the task
  85635. */
  85636. name,
  85637. /**
  85638. * Defines the location of the image to load
  85639. */
  85640. url) {
  85641. var _this = _super.call(this, name) || this;
  85642. _this.name = name;
  85643. _this.url = url;
  85644. return _this;
  85645. }
  85646. /**
  85647. * Execute the current task
  85648. * @param scene defines the scene where you want your assets to be loaded
  85649. * @param onSuccess is a callback called when the task is successfully executed
  85650. * @param onError is a callback called if an error occurs
  85651. */
  85652. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85653. var _this = this;
  85654. var img = new Image();
  85655. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85656. img.onload = function () {
  85657. _this.image = img;
  85658. onSuccess();
  85659. };
  85660. img.onerror = function (err) {
  85661. onError("Error loading image", err);
  85662. };
  85663. img.src = this.url;
  85664. };
  85665. return ImageAssetTask;
  85666. }(AbstractAssetTask));
  85667. BABYLON.ImageAssetTask = ImageAssetTask;
  85668. /**
  85669. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85670. */
  85671. var TextureAssetTask = /** @class */ (function (_super) {
  85672. __extends(TextureAssetTask, _super);
  85673. /**
  85674. * Creates a new TextureAssetTask object
  85675. * @param name defines the name of the task
  85676. * @param url defines the location of the file to load
  85677. * @param noMipmap defines if mipmap should not be generated (default is false)
  85678. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85679. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85680. */
  85681. function TextureAssetTask(
  85682. /**
  85683. * Defines the name of the task
  85684. */
  85685. name,
  85686. /**
  85687. * Defines the location of the file to load
  85688. */
  85689. url,
  85690. /**
  85691. * Defines if mipmap should not be generated (default is false)
  85692. */
  85693. noMipmap,
  85694. /**
  85695. * Defines if texture must be inverted on Y axis (default is false)
  85696. */
  85697. invertY,
  85698. /**
  85699. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85700. */
  85701. samplingMode) {
  85702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85703. var _this = _super.call(this, name) || this;
  85704. _this.name = name;
  85705. _this.url = url;
  85706. _this.noMipmap = noMipmap;
  85707. _this.invertY = invertY;
  85708. _this.samplingMode = samplingMode;
  85709. return _this;
  85710. }
  85711. /**
  85712. * Execute the current task
  85713. * @param scene defines the scene where you want your assets to be loaded
  85714. * @param onSuccess is a callback called when the task is successfully executed
  85715. * @param onError is a callback called if an error occurs
  85716. */
  85717. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85718. var onload = function () {
  85719. onSuccess();
  85720. };
  85721. var onerror = function (message, exception) {
  85722. onError(message, exception);
  85723. };
  85724. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85725. };
  85726. return TextureAssetTask;
  85727. }(AbstractAssetTask));
  85728. BABYLON.TextureAssetTask = TextureAssetTask;
  85729. /**
  85730. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85731. */
  85732. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85733. __extends(CubeTextureAssetTask, _super);
  85734. /**
  85735. * Creates a new CubeTextureAssetTask
  85736. * @param name defines the name of the task
  85737. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85738. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85739. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85740. * @param files defines the explicit list of files (undefined by default)
  85741. */
  85742. function CubeTextureAssetTask(
  85743. /**
  85744. * Defines the name of the task
  85745. */
  85746. name,
  85747. /**
  85748. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85749. */
  85750. url,
  85751. /**
  85752. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85753. */
  85754. extensions,
  85755. /**
  85756. * Defines if mipmaps should not be generated (default is false)
  85757. */
  85758. noMipmap,
  85759. /**
  85760. * Defines the explicit list of files (undefined by default)
  85761. */
  85762. files) {
  85763. var _this = _super.call(this, name) || this;
  85764. _this.name = name;
  85765. _this.url = url;
  85766. _this.extensions = extensions;
  85767. _this.noMipmap = noMipmap;
  85768. _this.files = files;
  85769. return _this;
  85770. }
  85771. /**
  85772. * Execute the current task
  85773. * @param scene defines the scene where you want your assets to be loaded
  85774. * @param onSuccess is a callback called when the task is successfully executed
  85775. * @param onError is a callback called if an error occurs
  85776. */
  85777. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85778. var onload = function () {
  85779. onSuccess();
  85780. };
  85781. var onerror = function (message, exception) {
  85782. onError(message, exception);
  85783. };
  85784. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85785. };
  85786. return CubeTextureAssetTask;
  85787. }(AbstractAssetTask));
  85788. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85789. /**
  85790. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85791. */
  85792. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85793. __extends(HDRCubeTextureAssetTask, _super);
  85794. /**
  85795. * Creates a new HDRCubeTextureAssetTask object
  85796. * @param name defines the name of the task
  85797. * @param url defines the location of the file to load
  85798. * @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.
  85799. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85800. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85801. * @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)
  85802. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85803. */
  85804. function HDRCubeTextureAssetTask(
  85805. /**
  85806. * Defines the name of the task
  85807. */
  85808. name,
  85809. /**
  85810. * Defines the location of the file to load
  85811. */
  85812. url,
  85813. /**
  85814. * 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.
  85815. */
  85816. size,
  85817. /**
  85818. * Defines if mipmaps should not be generated (default is false)
  85819. */
  85820. noMipmap,
  85821. /**
  85822. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85823. */
  85824. generateHarmonics,
  85825. /**
  85826. * 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)
  85827. */
  85828. useInGammaSpace,
  85829. /**
  85830. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85831. */
  85832. usePMREMGenerator) {
  85833. if (noMipmap === void 0) { noMipmap = false; }
  85834. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85835. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85836. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85837. var _this = _super.call(this, name) || this;
  85838. _this.name = name;
  85839. _this.url = url;
  85840. _this.size = size;
  85841. _this.noMipmap = noMipmap;
  85842. _this.generateHarmonics = generateHarmonics;
  85843. _this.useInGammaSpace = useInGammaSpace;
  85844. _this.usePMREMGenerator = usePMREMGenerator;
  85845. return _this;
  85846. }
  85847. /**
  85848. * Execute the current task
  85849. * @param scene defines the scene where you want your assets to be loaded
  85850. * @param onSuccess is a callback called when the task is successfully executed
  85851. * @param onError is a callback called if an error occurs
  85852. */
  85853. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85854. var onload = function () {
  85855. onSuccess();
  85856. };
  85857. var onerror = function (message, exception) {
  85858. onError(message, exception);
  85859. };
  85860. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85861. };
  85862. return HDRCubeTextureAssetTask;
  85863. }(AbstractAssetTask));
  85864. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85865. /**
  85866. * This class can be used to easily import assets into a scene
  85867. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85868. */
  85869. var AssetsManager = /** @class */ (function () {
  85870. /**
  85871. * Creates a new AssetsManager
  85872. * @param scene defines the scene to work on
  85873. */
  85874. function AssetsManager(scene) {
  85875. this._isLoading = false;
  85876. this._tasks = new Array();
  85877. this._waitingTasksCount = 0;
  85878. this._totalTasksCount = 0;
  85879. /**
  85880. * Observable called when all tasks are processed
  85881. */
  85882. this.onTaskSuccessObservable = new BABYLON.Observable();
  85883. /**
  85884. * Observable called when a task had an error
  85885. */
  85886. this.onTaskErrorObservable = new BABYLON.Observable();
  85887. /**
  85888. * Observable called when a task is successful
  85889. */
  85890. this.onTasksDoneObservable = new BABYLON.Observable();
  85891. /**
  85892. * Observable called when a task is done (whatever the result is)
  85893. */
  85894. this.onProgressObservable = new BABYLON.Observable();
  85895. /**
  85896. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85897. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85898. */
  85899. this.useDefaultLoadingScreen = true;
  85900. this._scene = scene;
  85901. }
  85902. /**
  85903. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85904. * @param taskName defines the name of the new task
  85905. * @param meshesNames defines the name of meshes to load
  85906. * @param rootUrl defines the root url to use to locate files
  85907. * @param sceneFilename defines the filename of the scene file
  85908. * @returns a new {BABYLON.MeshAssetTask} object
  85909. */
  85910. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85911. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85912. this._tasks.push(task);
  85913. return task;
  85914. };
  85915. /**
  85916. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85917. * @param taskName defines the name of the new task
  85918. * @param url defines the url of the file to load
  85919. * @returns a new {BABYLON.TextFileAssetTask} object
  85920. */
  85921. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85922. var task = new TextFileAssetTask(taskName, url);
  85923. this._tasks.push(task);
  85924. return task;
  85925. };
  85926. /**
  85927. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85928. * @param taskName defines the name of the new task
  85929. * @param url defines the url of the file to load
  85930. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85931. */
  85932. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85933. var task = new BinaryFileAssetTask(taskName, url);
  85934. this._tasks.push(task);
  85935. return task;
  85936. };
  85937. /**
  85938. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85939. * @param taskName defines the name of the new task
  85940. * @param url defines the url of the file to load
  85941. * @returns a new {BABYLON.ImageAssetTask} object
  85942. */
  85943. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85944. var task = new ImageAssetTask(taskName, url);
  85945. this._tasks.push(task);
  85946. return task;
  85947. };
  85948. /**
  85949. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85950. * @param taskName defines the name of the new task
  85951. * @param url defines the url of the file to load
  85952. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85953. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85954. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85955. * @returns a new {BABYLON.TextureAssetTask} object
  85956. */
  85957. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85958. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85959. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85960. this._tasks.push(task);
  85961. return task;
  85962. };
  85963. /**
  85964. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85965. * @param taskName defines the name of the new task
  85966. * @param url defines the url of the file to load
  85967. * @param extensions defines the extension to use to load the cube map (can be null)
  85968. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85969. * @param files defines the list of files to load (can be null)
  85970. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85971. */
  85972. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85973. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85974. this._tasks.push(task);
  85975. return task;
  85976. };
  85977. /**
  85978. *
  85979. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85980. * @param taskName defines the name of the new task
  85981. * @param url defines the url of the file to load
  85982. * @param size defines the size you want for the cubemap (can be null)
  85983. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85984. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85985. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85986. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85987. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85988. */
  85989. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85990. if (noMipmap === void 0) { noMipmap = false; }
  85991. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85992. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85993. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85994. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85995. this._tasks.push(task);
  85996. return task;
  85997. };
  85998. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85999. var _this = this;
  86000. this._waitingTasksCount--;
  86001. try {
  86002. if (task.taskState === AssetTaskState.DONE) {
  86003. // Let's remove successfull tasks
  86004. BABYLON.Tools.SetImmediate(function () {
  86005. var index = _this._tasks.indexOf(task);
  86006. if (index > -1) {
  86007. _this._tasks.splice(index, 1);
  86008. }
  86009. });
  86010. }
  86011. if (this.onProgress) {
  86012. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86013. }
  86014. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86015. }
  86016. catch (e) {
  86017. BABYLON.Tools.Error("Error running progress callbacks.");
  86018. console.log(e);
  86019. }
  86020. if (this._waitingTasksCount === 0) {
  86021. try {
  86022. if (this.onFinish) {
  86023. this.onFinish(this._tasks);
  86024. }
  86025. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86026. }
  86027. catch (e) {
  86028. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86029. console.log(e);
  86030. }
  86031. this._isLoading = false;
  86032. this._scene.getEngine().hideLoadingUI();
  86033. }
  86034. };
  86035. AssetsManager.prototype._runTask = function (task) {
  86036. var _this = this;
  86037. var done = function () {
  86038. try {
  86039. if (_this.onTaskSuccess) {
  86040. _this.onTaskSuccess(task);
  86041. }
  86042. _this.onTaskSuccessObservable.notifyObservers(task);
  86043. _this._decreaseWaitingTasksCount(task);
  86044. }
  86045. catch (e) {
  86046. error("Error executing task success callbacks", e);
  86047. }
  86048. };
  86049. var error = function (message, exception) {
  86050. task._setErrorObject(message, exception);
  86051. if (_this.onTaskError) {
  86052. _this.onTaskError(task);
  86053. }
  86054. _this.onTaskErrorObservable.notifyObservers(task);
  86055. _this._decreaseWaitingTasksCount(task);
  86056. };
  86057. task.run(this._scene, done, error);
  86058. };
  86059. /**
  86060. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86061. * @return the current instance of the {BABYLON.AssetsManager}
  86062. */
  86063. AssetsManager.prototype.reset = function () {
  86064. this._isLoading = false;
  86065. this._tasks = new Array();
  86066. return this;
  86067. };
  86068. /**
  86069. * Start the loading process
  86070. * @return the current instance of the {BABYLON.AssetsManager}
  86071. */
  86072. AssetsManager.prototype.load = function () {
  86073. if (this._isLoading) {
  86074. return this;
  86075. }
  86076. this._isLoading = true;
  86077. this._waitingTasksCount = this._tasks.length;
  86078. this._totalTasksCount = this._tasks.length;
  86079. if (this._waitingTasksCount === 0) {
  86080. this._isLoading = false;
  86081. if (this.onFinish) {
  86082. this.onFinish(this._tasks);
  86083. }
  86084. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86085. return this;
  86086. }
  86087. if (this.useDefaultLoadingScreen) {
  86088. this._scene.getEngine().displayLoadingUI();
  86089. }
  86090. for (var index = 0; index < this._tasks.length; index++) {
  86091. var task = this._tasks[index];
  86092. this._runTask(task);
  86093. }
  86094. return this;
  86095. };
  86096. return AssetsManager;
  86097. }());
  86098. BABYLON.AssetsManager = AssetsManager;
  86099. })(BABYLON || (BABYLON = {}));
  86100. //# sourceMappingURL=babylon.assetsManager.js.map
  86101. var BABYLON;
  86102. (function (BABYLON) {
  86103. var serializedGeometries = [];
  86104. var serializeGeometry = function (geometry, serializationGeometries) {
  86105. if (serializedGeometries[geometry.id]) {
  86106. return;
  86107. }
  86108. if (geometry.doNotSerialize) {
  86109. return;
  86110. }
  86111. if (geometry instanceof BABYLON.BoxGeometry) {
  86112. serializationGeometries.boxes.push(geometry.serialize());
  86113. }
  86114. else if (geometry instanceof BABYLON.SphereGeometry) {
  86115. serializationGeometries.spheres.push(geometry.serialize());
  86116. }
  86117. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86118. serializationGeometries.cylinders.push(geometry.serialize());
  86119. }
  86120. else if (geometry instanceof BABYLON.TorusGeometry) {
  86121. serializationGeometries.toruses.push(geometry.serialize());
  86122. }
  86123. else if (geometry instanceof BABYLON.GroundGeometry) {
  86124. serializationGeometries.grounds.push(geometry.serialize());
  86125. }
  86126. else if (geometry instanceof BABYLON.Plane) {
  86127. serializationGeometries.planes.push(geometry.serialize());
  86128. }
  86129. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86130. serializationGeometries.torusKnots.push(geometry.serialize());
  86131. }
  86132. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86133. throw new Error("Unknown primitive type");
  86134. }
  86135. else {
  86136. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86137. }
  86138. serializedGeometries[geometry.id] = true;
  86139. };
  86140. var serializeMesh = function (mesh, serializationScene) {
  86141. var serializationObject = {};
  86142. // Geometry
  86143. var geometry = mesh._geometry;
  86144. if (geometry) {
  86145. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86146. // 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
  86147. serializeGeometry(geometry, serializationScene.geometries);
  86148. }
  86149. }
  86150. // Custom
  86151. if (mesh.serialize) {
  86152. mesh.serialize(serializationObject);
  86153. }
  86154. return serializationObject;
  86155. };
  86156. var finalizeSingleMesh = function (mesh, serializationObject) {
  86157. //only works if the mesh is already loaded
  86158. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86159. //serialize material
  86160. if (mesh.material) {
  86161. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86162. serializationObject.materials = serializationObject.materials || [];
  86163. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86164. serializationObject.materials.push(mesh.material.serialize());
  86165. }
  86166. }
  86167. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86168. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86169. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86170. serializationObject.multiMaterials.push(mesh.material.serialize());
  86171. }
  86172. }
  86173. }
  86174. //serialize geometry
  86175. var geometry = mesh._geometry;
  86176. if (geometry) {
  86177. if (!serializationObject.geometries) {
  86178. serializationObject.geometries = {};
  86179. serializationObject.geometries.boxes = [];
  86180. serializationObject.geometries.spheres = [];
  86181. serializationObject.geometries.cylinders = [];
  86182. serializationObject.geometries.toruses = [];
  86183. serializationObject.geometries.grounds = [];
  86184. serializationObject.geometries.planes = [];
  86185. serializationObject.geometries.torusKnots = [];
  86186. serializationObject.geometries.vertexData = [];
  86187. }
  86188. serializeGeometry(geometry, serializationObject.geometries);
  86189. }
  86190. // Skeletons
  86191. if (mesh.skeleton) {
  86192. serializationObject.skeletons = serializationObject.skeletons || [];
  86193. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86194. }
  86195. //serialize the actual mesh
  86196. serializationObject.meshes = serializationObject.meshes || [];
  86197. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86198. }
  86199. };
  86200. var SceneSerializer = /** @class */ (function () {
  86201. function SceneSerializer() {
  86202. }
  86203. SceneSerializer.ClearCache = function () {
  86204. serializedGeometries = [];
  86205. };
  86206. SceneSerializer.Serialize = function (scene) {
  86207. var serializationObject = {};
  86208. SceneSerializer.ClearCache();
  86209. // Scene
  86210. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86211. serializationObject.autoClear = scene.autoClear;
  86212. serializationObject.clearColor = scene.clearColor.asArray();
  86213. serializationObject.ambientColor = scene.ambientColor.asArray();
  86214. serializationObject.gravity = scene.gravity.asArray();
  86215. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86216. serializationObject.workerCollisions = scene.workerCollisions;
  86217. // Fog
  86218. if (scene.fogMode && scene.fogMode !== 0) {
  86219. serializationObject.fogMode = scene.fogMode;
  86220. serializationObject.fogColor = scene.fogColor.asArray();
  86221. serializationObject.fogStart = scene.fogStart;
  86222. serializationObject.fogEnd = scene.fogEnd;
  86223. serializationObject.fogDensity = scene.fogDensity;
  86224. }
  86225. //Physics
  86226. if (scene.isPhysicsEnabled()) {
  86227. var physicEngine = scene.getPhysicsEngine();
  86228. if (physicEngine) {
  86229. serializationObject.physicsEnabled = true;
  86230. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86231. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86232. }
  86233. }
  86234. // Metadata
  86235. if (scene.metadata) {
  86236. serializationObject.metadata = scene.metadata;
  86237. }
  86238. // Morph targets
  86239. serializationObject.morphTargetManagers = [];
  86240. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86241. var abstractMesh = _a[_i];
  86242. var manager = abstractMesh.morphTargetManager;
  86243. if (manager) {
  86244. serializationObject.morphTargetManagers.push(manager.serialize());
  86245. }
  86246. }
  86247. // Lights
  86248. serializationObject.lights = [];
  86249. var index;
  86250. var light;
  86251. for (index = 0; index < scene.lights.length; index++) {
  86252. light = scene.lights[index];
  86253. if (!light.doNotSerialize) {
  86254. serializationObject.lights.push(light.serialize());
  86255. }
  86256. }
  86257. // Cameras
  86258. serializationObject.cameras = [];
  86259. for (index = 0; index < scene.cameras.length; index++) {
  86260. var camera = scene.cameras[index];
  86261. if (!camera.doNotSerialize) {
  86262. serializationObject.cameras.push(camera.serialize());
  86263. }
  86264. }
  86265. if (scene.activeCamera) {
  86266. serializationObject.activeCameraID = scene.activeCamera.id;
  86267. }
  86268. // Animations
  86269. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86270. // Materials
  86271. serializationObject.materials = [];
  86272. serializationObject.multiMaterials = [];
  86273. var material;
  86274. for (index = 0; index < scene.materials.length; index++) {
  86275. material = scene.materials[index];
  86276. if (!material.doNotSerialize) {
  86277. serializationObject.materials.push(material.serialize());
  86278. }
  86279. }
  86280. // MultiMaterials
  86281. serializationObject.multiMaterials = [];
  86282. for (index = 0; index < scene.multiMaterials.length; index++) {
  86283. var multiMaterial = scene.multiMaterials[index];
  86284. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86285. }
  86286. // Environment texture
  86287. if (scene.environmentTexture) {
  86288. serializationObject.environmentTexture = scene.environmentTexture.name;
  86289. }
  86290. // Skeletons
  86291. serializationObject.skeletons = [];
  86292. for (index = 0; index < scene.skeletons.length; index++) {
  86293. var skeleton = scene.skeletons[index];
  86294. if (!skeleton.doNotSerialize) {
  86295. serializationObject.skeletons.push(skeleton.serialize());
  86296. }
  86297. }
  86298. // Transform nodes
  86299. serializationObject.transformNodes = [];
  86300. for (index = 0; index < scene.transformNodes.length; index++) {
  86301. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86302. }
  86303. // Geometries
  86304. serializationObject.geometries = {};
  86305. serializationObject.geometries.boxes = [];
  86306. serializationObject.geometries.spheres = [];
  86307. serializationObject.geometries.cylinders = [];
  86308. serializationObject.geometries.toruses = [];
  86309. serializationObject.geometries.grounds = [];
  86310. serializationObject.geometries.planes = [];
  86311. serializationObject.geometries.torusKnots = [];
  86312. serializationObject.geometries.vertexData = [];
  86313. serializedGeometries = [];
  86314. var geometries = scene.getGeometries();
  86315. for (index = 0; index < geometries.length; index++) {
  86316. var geometry = geometries[index];
  86317. if (geometry.isReady()) {
  86318. serializeGeometry(geometry, serializationObject.geometries);
  86319. }
  86320. }
  86321. // Meshes
  86322. serializationObject.meshes = [];
  86323. for (index = 0; index < scene.meshes.length; index++) {
  86324. var abstractMesh = scene.meshes[index];
  86325. if (abstractMesh instanceof BABYLON.Mesh) {
  86326. var mesh = abstractMesh;
  86327. if (!mesh.doNotSerialize) {
  86328. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86329. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86330. }
  86331. }
  86332. }
  86333. }
  86334. // Particles Systems
  86335. serializationObject.particleSystems = [];
  86336. for (index = 0; index < scene.particleSystems.length; index++) {
  86337. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86338. }
  86339. // Lens flares
  86340. serializationObject.lensFlareSystems = [];
  86341. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86342. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86343. }
  86344. // Shadows
  86345. serializationObject.shadowGenerators = [];
  86346. for (index = 0; index < scene.lights.length; index++) {
  86347. light = scene.lights[index];
  86348. var shadowGenerator = light.getShadowGenerator();
  86349. if (shadowGenerator) {
  86350. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86351. }
  86352. }
  86353. // Action Manager
  86354. if (scene.actionManager) {
  86355. serializationObject.actions = scene.actionManager.serialize("scene");
  86356. }
  86357. // Audio
  86358. serializationObject.sounds = [];
  86359. for (index = 0; index < scene.soundTracks.length; index++) {
  86360. var soundtrack = scene.soundTracks[index];
  86361. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86362. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86363. }
  86364. }
  86365. return serializationObject;
  86366. };
  86367. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86368. if (withParents === void 0) { withParents = false; }
  86369. if (withChildren === void 0) { withChildren = false; }
  86370. var serializationObject = {};
  86371. SceneSerializer.ClearCache();
  86372. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86373. if (withParents || withChildren) {
  86374. //deliberate for loop! not for each, appended should be processed as well.
  86375. for (var i = 0; i < toSerialize.length; ++i) {
  86376. if (withChildren) {
  86377. toSerialize[i].getDescendants().forEach(function (node) {
  86378. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86379. toSerialize.push(node);
  86380. }
  86381. });
  86382. }
  86383. //make sure the array doesn't contain the object already
  86384. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86385. toSerialize.push(toSerialize[i].parent);
  86386. }
  86387. }
  86388. }
  86389. toSerialize.forEach(function (mesh) {
  86390. finalizeSingleMesh(mesh, serializationObject);
  86391. });
  86392. return serializationObject;
  86393. };
  86394. return SceneSerializer;
  86395. }());
  86396. BABYLON.SceneSerializer = SceneSerializer;
  86397. })(BABYLON || (BABYLON = {}));
  86398. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86399. var BABYLON;
  86400. (function (BABYLON) {
  86401. var ReflectionProbe = /** @class */ (function () {
  86402. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86403. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86404. var _this = this;
  86405. this.name = name;
  86406. this._viewMatrix = BABYLON.Matrix.Identity();
  86407. this._target = BABYLON.Vector3.Zero();
  86408. this._add = BABYLON.Vector3.Zero();
  86409. this._invertYAxis = false;
  86410. this.position = BABYLON.Vector3.Zero();
  86411. this._scene = scene;
  86412. this._scene.reflectionProbes.push(this);
  86413. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86414. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86415. switch (faceIndex) {
  86416. case 0:
  86417. _this._add.copyFromFloats(1, 0, 0);
  86418. break;
  86419. case 1:
  86420. _this._add.copyFromFloats(-1, 0, 0);
  86421. break;
  86422. case 2:
  86423. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86424. break;
  86425. case 3:
  86426. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86427. break;
  86428. case 4:
  86429. _this._add.copyFromFloats(0, 0, 1);
  86430. break;
  86431. case 5:
  86432. _this._add.copyFromFloats(0, 0, -1);
  86433. break;
  86434. }
  86435. if (_this._attachedMesh) {
  86436. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86437. }
  86438. _this.position.addToRef(_this._add, _this._target);
  86439. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86440. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86441. scene._forcedViewPosition = _this.position;
  86442. });
  86443. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86444. scene._forcedViewPosition = null;
  86445. scene.updateTransformMatrix(true);
  86446. });
  86447. if (scene.activeCamera) {
  86448. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86449. }
  86450. }
  86451. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86452. get: function () {
  86453. return this._renderTargetTexture.samples;
  86454. },
  86455. set: function (value) {
  86456. this._renderTargetTexture.samples = value;
  86457. },
  86458. enumerable: true,
  86459. configurable: true
  86460. });
  86461. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86462. get: function () {
  86463. return this._renderTargetTexture.refreshRate;
  86464. },
  86465. set: function (value) {
  86466. this._renderTargetTexture.refreshRate = value;
  86467. },
  86468. enumerable: true,
  86469. configurable: true
  86470. });
  86471. ReflectionProbe.prototype.getScene = function () {
  86472. return this._scene;
  86473. };
  86474. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86475. get: function () {
  86476. return this._renderTargetTexture;
  86477. },
  86478. enumerable: true,
  86479. configurable: true
  86480. });
  86481. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86482. get: function () {
  86483. return this._renderTargetTexture.renderList;
  86484. },
  86485. enumerable: true,
  86486. configurable: true
  86487. });
  86488. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86489. this._attachedMesh = mesh;
  86490. };
  86491. /**
  86492. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86493. *
  86494. * @param renderingGroupId The rendering group id corresponding to its index
  86495. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86496. */
  86497. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86498. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86499. };
  86500. ReflectionProbe.prototype.dispose = function () {
  86501. var index = this._scene.reflectionProbes.indexOf(this);
  86502. if (index !== -1) {
  86503. // Remove from the scene if found
  86504. this._scene.reflectionProbes.splice(index, 1);
  86505. }
  86506. if (this._renderTargetTexture) {
  86507. this._renderTargetTexture.dispose();
  86508. this._renderTargetTexture = null;
  86509. }
  86510. };
  86511. return ReflectionProbe;
  86512. }());
  86513. BABYLON.ReflectionProbe = ReflectionProbe;
  86514. })(BABYLON || (BABYLON = {}));
  86515. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86516. var BABYLON;
  86517. (function (BABYLON) {
  86518. var Layer = /** @class */ (function () {
  86519. function Layer(name, imgUrl, scene, isBackground, color) {
  86520. this.name = name;
  86521. this.scale = new BABYLON.Vector2(1, 1);
  86522. this.offset = new BABYLON.Vector2(0, 0);
  86523. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86524. this.layerMask = 0x0FFFFFFF;
  86525. this._vertexBuffers = {};
  86526. // Events
  86527. /**
  86528. * An event triggered when the layer is disposed.
  86529. * @type {BABYLON.Observable}
  86530. */
  86531. this.onDisposeObservable = new BABYLON.Observable();
  86532. /**
  86533. * An event triggered before rendering the scene
  86534. * @type {BABYLON.Observable}
  86535. */
  86536. this.onBeforeRenderObservable = new BABYLON.Observable();
  86537. /**
  86538. * An event triggered after rendering the scene
  86539. * @type {BABYLON.Observable}
  86540. */
  86541. this.onAfterRenderObservable = new BABYLON.Observable();
  86542. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86543. this.isBackground = isBackground === undefined ? true : isBackground;
  86544. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86545. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86546. this._scene.layers.push(this);
  86547. var engine = this._scene.getEngine();
  86548. // VBO
  86549. var vertices = [];
  86550. vertices.push(1, 1);
  86551. vertices.push(-1, 1);
  86552. vertices.push(-1, -1);
  86553. vertices.push(1, -1);
  86554. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86555. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86556. this._createIndexBuffer();
  86557. // Effects
  86558. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86559. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86560. }
  86561. Object.defineProperty(Layer.prototype, "onDispose", {
  86562. set: function (callback) {
  86563. if (this._onDisposeObserver) {
  86564. this.onDisposeObservable.remove(this._onDisposeObserver);
  86565. }
  86566. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86567. },
  86568. enumerable: true,
  86569. configurable: true
  86570. });
  86571. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86572. set: function (callback) {
  86573. if (this._onBeforeRenderObserver) {
  86574. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86575. }
  86576. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86577. },
  86578. enumerable: true,
  86579. configurable: true
  86580. });
  86581. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86582. set: function (callback) {
  86583. if (this._onAfterRenderObserver) {
  86584. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86585. }
  86586. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86587. },
  86588. enumerable: true,
  86589. configurable: true
  86590. });
  86591. Layer.prototype._createIndexBuffer = function () {
  86592. var engine = this._scene.getEngine();
  86593. // Indices
  86594. var indices = [];
  86595. indices.push(0);
  86596. indices.push(1);
  86597. indices.push(2);
  86598. indices.push(0);
  86599. indices.push(2);
  86600. indices.push(3);
  86601. this._indexBuffer = engine.createIndexBuffer(indices);
  86602. };
  86603. Layer.prototype._rebuild = function () {
  86604. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86605. if (vb) {
  86606. vb._rebuild();
  86607. }
  86608. this._createIndexBuffer();
  86609. };
  86610. Layer.prototype.render = function () {
  86611. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86612. // Check
  86613. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86614. return;
  86615. var engine = this._scene.getEngine();
  86616. this.onBeforeRenderObservable.notifyObservers(this);
  86617. // Render
  86618. engine.enableEffect(currentEffect);
  86619. engine.setState(false);
  86620. // Texture
  86621. currentEffect.setTexture("textureSampler", this.texture);
  86622. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86623. // Color
  86624. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86625. // Scale / offset
  86626. currentEffect.setVector2("offset", this.offset);
  86627. currentEffect.setVector2("scale", this.scale);
  86628. // VBOs
  86629. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86630. // Draw order
  86631. if (!this.alphaTest) {
  86632. engine.setAlphaMode(this.alphaBlendingMode);
  86633. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86634. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86635. }
  86636. else {
  86637. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86638. }
  86639. this.onAfterRenderObservable.notifyObservers(this);
  86640. };
  86641. Layer.prototype.dispose = function () {
  86642. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86643. if (vertexBuffer) {
  86644. vertexBuffer.dispose();
  86645. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86646. }
  86647. if (this._indexBuffer) {
  86648. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86649. this._indexBuffer = null;
  86650. }
  86651. if (this.texture) {
  86652. this.texture.dispose();
  86653. this.texture = null;
  86654. }
  86655. // Remove from scene
  86656. var index = this._scene.layers.indexOf(this);
  86657. this._scene.layers.splice(index, 1);
  86658. // Callback
  86659. this.onDisposeObservable.notifyObservers(this);
  86660. this.onDisposeObservable.clear();
  86661. this.onAfterRenderObservable.clear();
  86662. this.onBeforeRenderObservable.clear();
  86663. };
  86664. return Layer;
  86665. }());
  86666. BABYLON.Layer = Layer;
  86667. })(BABYLON || (BABYLON = {}));
  86668. //# sourceMappingURL=babylon.layer.js.map
  86669. var BABYLON;
  86670. (function (BABYLON) {
  86671. var TextureTools = /** @class */ (function () {
  86672. function TextureTools() {
  86673. }
  86674. /**
  86675. * Uses the GPU to create a copy texture rescaled at a given size
  86676. * @param texture Texture to copy from
  86677. * @param width Desired width
  86678. * @param height Desired height
  86679. * @return Generated texture
  86680. */
  86681. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86682. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86683. var scene = texture.getScene();
  86684. var engine = scene.getEngine();
  86685. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86686. rtt.wrapU = texture.wrapU;
  86687. rtt.wrapV = texture.wrapV;
  86688. rtt.uOffset = texture.uOffset;
  86689. rtt.vOffset = texture.vOffset;
  86690. rtt.uScale = texture.uScale;
  86691. rtt.vScale = texture.vScale;
  86692. rtt.uAng = texture.uAng;
  86693. rtt.vAng = texture.vAng;
  86694. rtt.wAng = texture.wAng;
  86695. rtt.coordinatesIndex = texture.coordinatesIndex;
  86696. rtt.level = texture.level;
  86697. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86698. rtt._texture.isReady = false;
  86699. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86700. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86701. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86702. passPostProcess.getEffect().executeWhenCompiled(function () {
  86703. passPostProcess.onApply = function (effect) {
  86704. effect.setTexture("textureSampler", texture);
  86705. };
  86706. var internalTexture = rtt.getInternalTexture();
  86707. if (internalTexture) {
  86708. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86709. engine.unBindFramebuffer(internalTexture);
  86710. rtt.disposeFramebufferObjects();
  86711. passPostProcess.dispose();
  86712. internalTexture.isReady = true;
  86713. }
  86714. });
  86715. return rtt;
  86716. };
  86717. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86718. if (!scene._environmentBRDFTexture) {
  86719. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86720. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86721. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86722. scene._environmentBRDFTexture = texture;
  86723. }
  86724. return scene._environmentBRDFTexture;
  86725. };
  86726. 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=";
  86727. return TextureTools;
  86728. }());
  86729. BABYLON.TextureTools = TextureTools;
  86730. })(BABYLON || (BABYLON = {}));
  86731. //# sourceMappingURL=babylon.textureTools.js.map
  86732. var BABYLON;
  86733. (function (BABYLON) {
  86734. var FramingBehavior = /** @class */ (function () {
  86735. function FramingBehavior() {
  86736. this._mode = FramingBehavior.FitFrustumSidesMode;
  86737. this._radiusScale = 1.0;
  86738. this._positionScale = 0.5;
  86739. this._defaultElevation = 0.3;
  86740. this._elevationReturnTime = 1500;
  86741. this._elevationReturnWaitTime = 1000;
  86742. this._zoomStopsAnimation = false;
  86743. this._framingTime = 1500;
  86744. this._isPointerDown = false;
  86745. this._lastInteractionTime = -Infinity;
  86746. // Framing control
  86747. this._animatables = new Array();
  86748. this._betaIsAnimating = false;
  86749. }
  86750. Object.defineProperty(FramingBehavior.prototype, "name", {
  86751. get: function () {
  86752. return "Framing";
  86753. },
  86754. enumerable: true,
  86755. configurable: true
  86756. });
  86757. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86758. /**
  86759. * Gets current mode used by the behavior.
  86760. */
  86761. get: function () {
  86762. return this._mode;
  86763. },
  86764. /**
  86765. * Sets the current mode used by the behavior
  86766. */
  86767. set: function (mode) {
  86768. this._mode = mode;
  86769. },
  86770. enumerable: true,
  86771. configurable: true
  86772. });
  86773. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86774. /**
  86775. * Gets the scale applied to the radius
  86776. */
  86777. get: function () {
  86778. return this._radiusScale;
  86779. },
  86780. /**
  86781. * Sets the scale applied to the radius (1 by default)
  86782. */
  86783. set: function (radius) {
  86784. this._radiusScale = radius;
  86785. },
  86786. enumerable: true,
  86787. configurable: true
  86788. });
  86789. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86790. /**
  86791. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86792. */
  86793. get: function () {
  86794. return this._positionScale;
  86795. },
  86796. /**
  86797. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86798. */
  86799. set: function (scale) {
  86800. this._positionScale = scale;
  86801. },
  86802. enumerable: true,
  86803. configurable: true
  86804. });
  86805. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86806. /**
  86807. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86808. * behaviour is triggered, in radians.
  86809. */
  86810. get: function () {
  86811. return this._defaultElevation;
  86812. },
  86813. /**
  86814. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86815. * behaviour is triggered, in radians.
  86816. */
  86817. set: function (elevation) {
  86818. this._defaultElevation = elevation;
  86819. },
  86820. enumerable: true,
  86821. configurable: true
  86822. });
  86823. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86824. /**
  86825. * Gets the time (in milliseconds) taken to return to the default beta position.
  86826. * Negative value indicates camera should not return to default.
  86827. */
  86828. get: function () {
  86829. return this._elevationReturnTime;
  86830. },
  86831. /**
  86832. * Sets the time (in milliseconds) taken to return to the default beta position.
  86833. * Negative value indicates camera should not return to default.
  86834. */
  86835. set: function (speed) {
  86836. this._elevationReturnTime = speed;
  86837. },
  86838. enumerable: true,
  86839. configurable: true
  86840. });
  86841. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86842. /**
  86843. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86844. */
  86845. get: function () {
  86846. return this._elevationReturnWaitTime;
  86847. },
  86848. /**
  86849. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86850. */
  86851. set: function (time) {
  86852. this._elevationReturnWaitTime = time;
  86853. },
  86854. enumerable: true,
  86855. configurable: true
  86856. });
  86857. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86858. /**
  86859. * Gets the flag that indicates if user zooming should stop animation.
  86860. */
  86861. get: function () {
  86862. return this._zoomStopsAnimation;
  86863. },
  86864. /**
  86865. * Sets the flag that indicates if user zooming should stop animation.
  86866. */
  86867. set: function (flag) {
  86868. this._zoomStopsAnimation = flag;
  86869. },
  86870. enumerable: true,
  86871. configurable: true
  86872. });
  86873. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86874. /**
  86875. * Gets the transition time when framing the mesh, in milliseconds
  86876. */
  86877. get: function () {
  86878. return this._framingTime;
  86879. },
  86880. /**
  86881. * Sets the transition time when framing the mesh, in milliseconds
  86882. */
  86883. set: function (time) {
  86884. this._framingTime = time;
  86885. },
  86886. enumerable: true,
  86887. configurable: true
  86888. });
  86889. FramingBehavior.prototype.init = function () {
  86890. // Do notihng
  86891. };
  86892. FramingBehavior.prototype.attach = function (camera) {
  86893. var _this = this;
  86894. this._attachedCamera = camera;
  86895. var scene = this._attachedCamera.getScene();
  86896. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86897. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86898. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86899. _this._isPointerDown = true;
  86900. return;
  86901. }
  86902. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86903. _this._isPointerDown = false;
  86904. }
  86905. });
  86906. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86907. if (mesh) {
  86908. _this.zoomOnMesh(mesh);
  86909. }
  86910. });
  86911. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86912. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86913. _this._applyUserInteraction();
  86914. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86915. // back to the default position after a given timeout
  86916. _this._maintainCameraAboveGround();
  86917. });
  86918. };
  86919. FramingBehavior.prototype.detach = function () {
  86920. if (!this._attachedCamera) {
  86921. return;
  86922. }
  86923. var scene = this._attachedCamera.getScene();
  86924. if (this._onPrePointerObservableObserver) {
  86925. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86926. }
  86927. if (this._onAfterCheckInputsObserver) {
  86928. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86929. }
  86930. if (this._onMeshTargetChangedObserver) {
  86931. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86932. }
  86933. this._attachedCamera = null;
  86934. };
  86935. /**
  86936. * Targets the given mesh and updates zoom level accordingly.
  86937. * @param mesh The mesh to target.
  86938. * @param radius Optional. If a cached radius position already exists, overrides default.
  86939. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86940. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86941. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86942. */
  86943. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86944. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86945. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86946. mesh.computeWorldMatrix(true);
  86947. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86948. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86949. };
  86950. /**
  86951. * Targets the given mesh with its children and updates zoom level accordingly.
  86952. * @param mesh The mesh to target.
  86953. * @param radius Optional. If a cached radius position already exists, overrides default.
  86954. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86955. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86956. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86957. */
  86958. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86959. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86960. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86961. mesh.computeWorldMatrix(true);
  86962. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86963. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86964. };
  86965. /**
  86966. * Targets the given meshes with their children and updates zoom level accordingly.
  86967. * @param meshes The mesh to target.
  86968. * @param radius Optional. If a cached radius position already exists, overrides default.
  86969. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86970. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86971. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86972. */
  86973. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86974. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86975. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86976. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86977. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86978. for (var i = 0; i < meshes.length; i++) {
  86979. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86980. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86981. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86982. }
  86983. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86984. };
  86985. /**
  86986. * Targets the given mesh and updates zoom level accordingly.
  86987. * @param mesh The mesh to target.
  86988. * @param radius Optional. If a cached radius position already exists, overrides default.
  86989. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86990. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86991. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86992. */
  86993. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86994. var _this = this;
  86995. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86996. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86997. var zoomTarget;
  86998. if (!this._attachedCamera) {
  86999. return;
  87000. }
  87001. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87002. var bottom = minimumWorld.y;
  87003. var top = maximumWorld.y;
  87004. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87005. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87006. if (focusOnOriginXZ) {
  87007. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87008. }
  87009. else {
  87010. var centerWorld = minimumWorld.add(radiusWorld);
  87011. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87012. }
  87013. if (!this._vectorTransition) {
  87014. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87015. }
  87016. this._betaIsAnimating = true;
  87017. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87018. if (animatable) {
  87019. this._animatables.push(animatable);
  87020. }
  87021. // sets the radius and lower radius bounds
  87022. // Small delta ensures camera is not always at lower zoom limit.
  87023. var radius = 0;
  87024. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87025. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87026. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87027. radius = position;
  87028. }
  87029. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87030. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87031. if (this._attachedCamera.lowerRadiusLimit === null) {
  87032. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87033. }
  87034. }
  87035. // Set sensibilities
  87036. var extend = maximumWorld.subtract(minimumWorld).length();
  87037. this._attachedCamera.panningSensibility = 5000 / extend;
  87038. this._attachedCamera.wheelPrecision = 100 / radius;
  87039. // transition to new radius
  87040. if (!this._radiusTransition) {
  87041. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87042. }
  87043. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87044. if (onAnimationEnd) {
  87045. onAnimationEnd();
  87046. }
  87047. if (_this._attachedCamera) {
  87048. _this._attachedCamera.storeState();
  87049. }
  87050. });
  87051. if (animatable) {
  87052. this._animatables.push(animatable);
  87053. }
  87054. };
  87055. /**
  87056. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87057. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87058. * frustum width.
  87059. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87060. * to fully enclose the mesh in the viewing frustum.
  87061. */
  87062. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87063. var size = maximumWorld.subtract(minimumWorld);
  87064. var boxVectorGlobalDiagonal = size.length();
  87065. var frustumSlope = this._getFrustumSlope();
  87066. // Formula for setting distance
  87067. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87068. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87069. // Horizon distance
  87070. var radius = radiusWithoutFraming * this._radiusScale;
  87071. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87072. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87073. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87074. var camera = this._attachedCamera;
  87075. if (!camera) {
  87076. return 0;
  87077. }
  87078. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87079. // Don't exceed the requested limit
  87080. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87081. }
  87082. // Don't exceed the upper radius limit
  87083. if (camera.upperRadiusLimit) {
  87084. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87085. }
  87086. return distance;
  87087. };
  87088. /**
  87089. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87090. * is automatically returned to its default position (expected to be above ground plane).
  87091. */
  87092. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87093. var _this = this;
  87094. if (this._elevationReturnTime < 0) {
  87095. return;
  87096. }
  87097. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87098. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87099. var limitBeta = Math.PI * 0.5;
  87100. // Bring the camera back up if below the ground plane
  87101. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87102. this._betaIsAnimating = true;
  87103. //Transition to new position
  87104. this.stopAllAnimations();
  87105. if (!this._betaTransition) {
  87106. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87107. }
  87108. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87109. _this._clearAnimationLocks();
  87110. _this.stopAllAnimations();
  87111. });
  87112. if (animatabe) {
  87113. this._animatables.push(animatabe);
  87114. }
  87115. }
  87116. };
  87117. /**
  87118. * Returns the frustum slope based on the canvas ratio and camera FOV
  87119. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87120. */
  87121. FramingBehavior.prototype._getFrustumSlope = function () {
  87122. // Calculate the viewport ratio
  87123. // Aspect Ratio is Height/Width.
  87124. var camera = this._attachedCamera;
  87125. if (!camera) {
  87126. return BABYLON.Vector2.Zero();
  87127. }
  87128. var engine = camera.getScene().getEngine();
  87129. var aspectRatio = engine.getAspectRatio(camera);
  87130. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87131. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87132. var frustumSlopeY = Math.tan(camera.fov / 2);
  87133. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87134. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87135. // along the forward vector.
  87136. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87137. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87138. };
  87139. /**
  87140. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87141. */
  87142. FramingBehavior.prototype._clearAnimationLocks = function () {
  87143. this._betaIsAnimating = false;
  87144. };
  87145. /**
  87146. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87147. */
  87148. FramingBehavior.prototype._applyUserInteraction = function () {
  87149. if (this.isUserIsMoving) {
  87150. this._lastInteractionTime = BABYLON.Tools.Now;
  87151. this.stopAllAnimations();
  87152. this._clearAnimationLocks();
  87153. }
  87154. };
  87155. /**
  87156. * Stops and removes all animations that have been applied to the camera
  87157. */
  87158. FramingBehavior.prototype.stopAllAnimations = function () {
  87159. if (this._attachedCamera) {
  87160. this._attachedCamera.animations = [];
  87161. }
  87162. while (this._animatables.length) {
  87163. if (this._animatables[0]) {
  87164. this._animatables[0].onAnimationEnd = null;
  87165. this._animatables[0].stop();
  87166. }
  87167. this._animatables.shift();
  87168. }
  87169. };
  87170. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87171. /**
  87172. * Gets a value indicating if the user is moving the camera
  87173. */
  87174. get: function () {
  87175. if (!this._attachedCamera) {
  87176. return false;
  87177. }
  87178. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87179. this._attachedCamera.inertialBetaOffset !== 0 ||
  87180. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87181. this._attachedCamera.inertialPanningX !== 0 ||
  87182. this._attachedCamera.inertialPanningY !== 0 ||
  87183. this._isPointerDown;
  87184. },
  87185. enumerable: true,
  87186. configurable: true
  87187. });
  87188. /**
  87189. * The easing function used by animations
  87190. */
  87191. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87192. /**
  87193. * The easing mode used by animations
  87194. */
  87195. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87196. // Statics
  87197. /**
  87198. * The camera can move all the way towards the mesh.
  87199. */
  87200. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87201. /**
  87202. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87203. */
  87204. FramingBehavior.FitFrustumSidesMode = 1;
  87205. return FramingBehavior;
  87206. }());
  87207. BABYLON.FramingBehavior = FramingBehavior;
  87208. })(BABYLON || (BABYLON = {}));
  87209. //# sourceMappingURL=babylon.framingBehavior.js.map
  87210. var BABYLON;
  87211. (function (BABYLON) {
  87212. /**
  87213. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87214. */
  87215. var BouncingBehavior = /** @class */ (function () {
  87216. function BouncingBehavior() {
  87217. /**
  87218. * The duration of the animation, in milliseconds
  87219. */
  87220. this.transitionDuration = 450;
  87221. /**
  87222. * Length of the distance animated by the transition when lower radius is reached
  87223. */
  87224. this.lowerRadiusTransitionRange = 2;
  87225. /**
  87226. * Length of the distance animated by the transition when upper radius is reached
  87227. */
  87228. this.upperRadiusTransitionRange = -2;
  87229. this._autoTransitionRange = false;
  87230. // Animations
  87231. this._radiusIsAnimating = false;
  87232. this._radiusBounceTransition = null;
  87233. this._animatables = new Array();
  87234. }
  87235. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87236. get: function () {
  87237. return "Bouncing";
  87238. },
  87239. enumerable: true,
  87240. configurable: true
  87241. });
  87242. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87243. /**
  87244. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87245. */
  87246. get: function () {
  87247. return this._autoTransitionRange;
  87248. },
  87249. /**
  87250. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87251. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87252. */
  87253. set: function (value) {
  87254. var _this = this;
  87255. if (this._autoTransitionRange === value) {
  87256. return;
  87257. }
  87258. this._autoTransitionRange = value;
  87259. var camera = this._attachedCamera;
  87260. if (!camera) {
  87261. return;
  87262. }
  87263. if (value) {
  87264. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87265. if (!mesh) {
  87266. return;
  87267. }
  87268. mesh.computeWorldMatrix(true);
  87269. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87270. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87271. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87272. });
  87273. }
  87274. else if (this._onMeshTargetChangedObserver) {
  87275. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87276. }
  87277. },
  87278. enumerable: true,
  87279. configurable: true
  87280. });
  87281. BouncingBehavior.prototype.init = function () {
  87282. // Do notihng
  87283. };
  87284. BouncingBehavior.prototype.attach = function (camera) {
  87285. var _this = this;
  87286. this._attachedCamera = camera;
  87287. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87288. if (!_this._attachedCamera) {
  87289. return;
  87290. }
  87291. // Add the bounce animation to the lower radius limit
  87292. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87293. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87294. }
  87295. // Add the bounce animation to the upper radius limit
  87296. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87297. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87298. }
  87299. });
  87300. };
  87301. BouncingBehavior.prototype.detach = function () {
  87302. if (!this._attachedCamera) {
  87303. return;
  87304. }
  87305. if (this._onAfterCheckInputsObserver) {
  87306. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87307. }
  87308. if (this._onMeshTargetChangedObserver) {
  87309. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87310. }
  87311. this._attachedCamera = null;
  87312. };
  87313. /**
  87314. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87315. * @param radiusLimit The limit to check against.
  87316. * @return Bool to indicate if at limit.
  87317. */
  87318. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87319. if (!this._attachedCamera) {
  87320. return false;
  87321. }
  87322. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87323. return true;
  87324. }
  87325. return false;
  87326. };
  87327. /**
  87328. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87329. * @param radiusDelta The delta by which to animate to. Can be negative.
  87330. */
  87331. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87332. var _this = this;
  87333. if (!this._attachedCamera) {
  87334. return;
  87335. }
  87336. if (!this._radiusBounceTransition) {
  87337. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87338. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87339. }
  87340. // Prevent zoom until bounce has completed
  87341. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87342. this._attachedCamera.wheelPrecision = Infinity;
  87343. this._attachedCamera.inertialRadiusOffset = 0;
  87344. // Animate to the radius limit
  87345. this.stopAllAnimations();
  87346. this._radiusIsAnimating = true;
  87347. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87348. if (animatable) {
  87349. this._animatables.push(animatable);
  87350. }
  87351. };
  87352. /**
  87353. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87354. */
  87355. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87356. this._radiusIsAnimating = false;
  87357. if (this._attachedCamera) {
  87358. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87359. }
  87360. };
  87361. /**
  87362. * Stops and removes all animations that have been applied to the camera
  87363. */
  87364. BouncingBehavior.prototype.stopAllAnimations = function () {
  87365. if (this._attachedCamera) {
  87366. this._attachedCamera.animations = [];
  87367. }
  87368. while (this._animatables.length) {
  87369. this._animatables[0].onAnimationEnd = null;
  87370. this._animatables[0].stop();
  87371. this._animatables.shift();
  87372. }
  87373. };
  87374. /**
  87375. * The easing function used by animations
  87376. */
  87377. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87378. /**
  87379. * The easing mode used by animations
  87380. */
  87381. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87382. return BouncingBehavior;
  87383. }());
  87384. BABYLON.BouncingBehavior = BouncingBehavior;
  87385. })(BABYLON || (BABYLON = {}));
  87386. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87387. var BABYLON;
  87388. (function (BABYLON) {
  87389. var AutoRotationBehavior = /** @class */ (function () {
  87390. function AutoRotationBehavior() {
  87391. this._zoomStopsAnimation = false;
  87392. this._idleRotationSpeed = 0.05;
  87393. this._idleRotationWaitTime = 2000;
  87394. this._idleRotationSpinupTime = 2000;
  87395. this._isPointerDown = false;
  87396. this._lastFrameTime = null;
  87397. this._lastInteractionTime = -Infinity;
  87398. this._cameraRotationSpeed = 0;
  87399. this._lastFrameRadius = 0;
  87400. }
  87401. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87402. get: function () {
  87403. return "AutoRotation";
  87404. },
  87405. enumerable: true,
  87406. configurable: true
  87407. });
  87408. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87409. /**
  87410. * Gets the flag that indicates if user zooming should stop animation.
  87411. */
  87412. get: function () {
  87413. return this._zoomStopsAnimation;
  87414. },
  87415. /**
  87416. * Sets the flag that indicates if user zooming should stop animation.
  87417. */
  87418. set: function (flag) {
  87419. this._zoomStopsAnimation = flag;
  87420. },
  87421. enumerable: true,
  87422. configurable: true
  87423. });
  87424. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87425. /**
  87426. * Gets the default speed at which the camera rotates around the model.
  87427. */
  87428. get: function () {
  87429. return this._idleRotationSpeed;
  87430. },
  87431. /**
  87432. * Sets the default speed at which the camera rotates around the model.
  87433. */
  87434. set: function (speed) {
  87435. this._idleRotationSpeed = speed;
  87436. },
  87437. enumerable: true,
  87438. configurable: true
  87439. });
  87440. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87441. /**
  87442. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87443. */
  87444. get: function () {
  87445. return this._idleRotationWaitTime;
  87446. },
  87447. /**
  87448. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87449. */
  87450. set: function (time) {
  87451. this._idleRotationWaitTime = time;
  87452. },
  87453. enumerable: true,
  87454. configurable: true
  87455. });
  87456. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87457. /**
  87458. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87459. */
  87460. get: function () {
  87461. return this._idleRotationSpinupTime;
  87462. },
  87463. /**
  87464. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87465. */
  87466. set: function (time) {
  87467. this._idleRotationSpinupTime = time;
  87468. },
  87469. enumerable: true,
  87470. configurable: true
  87471. });
  87472. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87473. /**
  87474. * Gets a value indicating if the camera is currently rotating because of this behavior
  87475. */
  87476. get: function () {
  87477. return Math.abs(this._cameraRotationSpeed) > 0;
  87478. },
  87479. enumerable: true,
  87480. configurable: true
  87481. });
  87482. AutoRotationBehavior.prototype.init = function () {
  87483. // Do notihng
  87484. };
  87485. AutoRotationBehavior.prototype.attach = function (camera) {
  87486. var _this = this;
  87487. this._attachedCamera = camera;
  87488. var scene = this._attachedCamera.getScene();
  87489. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87490. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87491. _this._isPointerDown = true;
  87492. return;
  87493. }
  87494. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87495. _this._isPointerDown = false;
  87496. }
  87497. });
  87498. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87499. var now = BABYLON.Tools.Now;
  87500. var dt = 0;
  87501. if (_this._lastFrameTime != null) {
  87502. dt = now - _this._lastFrameTime;
  87503. }
  87504. _this._lastFrameTime = now;
  87505. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87506. _this._applyUserInteraction();
  87507. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87508. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87509. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87510. // Step camera rotation by rotation speed
  87511. if (_this._attachedCamera) {
  87512. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87513. }
  87514. });
  87515. };
  87516. AutoRotationBehavior.prototype.detach = function () {
  87517. if (!this._attachedCamera) {
  87518. return;
  87519. }
  87520. var scene = this._attachedCamera.getScene();
  87521. if (this._onPrePointerObservableObserver) {
  87522. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87523. }
  87524. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87525. this._attachedCamera = null;
  87526. };
  87527. /**
  87528. * Returns true if user is scrolling.
  87529. * @return true if user is scrolling.
  87530. */
  87531. AutoRotationBehavior.prototype._userIsZooming = function () {
  87532. if (!this._attachedCamera) {
  87533. return false;
  87534. }
  87535. return this._attachedCamera.inertialRadiusOffset !== 0;
  87536. };
  87537. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87538. if (!this._attachedCamera) {
  87539. return false;
  87540. }
  87541. var zoomHasHitLimit = false;
  87542. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87543. zoomHasHitLimit = true;
  87544. }
  87545. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87546. this._lastFrameRadius = this._attachedCamera.radius;
  87547. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87548. };
  87549. /**
  87550. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87551. */
  87552. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87553. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87554. this._lastInteractionTime = BABYLON.Tools.Now;
  87555. }
  87556. };
  87557. // Tools
  87558. AutoRotationBehavior.prototype._userIsMoving = function () {
  87559. if (!this._attachedCamera) {
  87560. return false;
  87561. }
  87562. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87563. this._attachedCamera.inertialBetaOffset !== 0 ||
  87564. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87565. this._attachedCamera.inertialPanningX !== 0 ||
  87566. this._attachedCamera.inertialPanningY !== 0 ||
  87567. this._isPointerDown;
  87568. };
  87569. return AutoRotationBehavior;
  87570. }());
  87571. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87572. })(BABYLON || (BABYLON = {}));
  87573. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87574. var BABYLON;
  87575. (function (BABYLON) {
  87576. /**
  87577. * This class can be used to get instrumentation data from a Babylon engine
  87578. */
  87579. var EngineInstrumentation = /** @class */ (function () {
  87580. function EngineInstrumentation(engine) {
  87581. this.engine = engine;
  87582. this._captureGPUFrameTime = false;
  87583. this._gpuFrameTime = new BABYLON.PerfCounter();
  87584. this._captureShaderCompilationTime = false;
  87585. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87586. // Observers
  87587. this._onBeginFrameObserver = null;
  87588. this._onEndFrameObserver = null;
  87589. this._onBeforeShaderCompilationObserver = null;
  87590. this._onAfterShaderCompilationObserver = null;
  87591. }
  87592. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87593. // Properties
  87594. /**
  87595. * Gets the perf counter used for GPU frame time
  87596. */
  87597. get: function () {
  87598. return this._gpuFrameTime;
  87599. },
  87600. enumerable: true,
  87601. configurable: true
  87602. });
  87603. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87604. /**
  87605. * Gets the GPU frame time capture status
  87606. */
  87607. get: function () {
  87608. return this._captureGPUFrameTime;
  87609. },
  87610. /**
  87611. * Enable or disable the GPU frame time capture
  87612. */
  87613. set: function (value) {
  87614. var _this = this;
  87615. if (value === this._captureGPUFrameTime) {
  87616. return;
  87617. }
  87618. this._captureGPUFrameTime = value;
  87619. if (value) {
  87620. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87621. if (!_this._gpuFrameTimeToken) {
  87622. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87623. }
  87624. });
  87625. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87626. if (!_this._gpuFrameTimeToken) {
  87627. return;
  87628. }
  87629. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87630. if (time > -1) {
  87631. _this._gpuFrameTimeToken = null;
  87632. _this._gpuFrameTime.fetchNewFrame();
  87633. _this._gpuFrameTime.addCount(time, true);
  87634. }
  87635. });
  87636. }
  87637. else {
  87638. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87639. this._onBeginFrameObserver = null;
  87640. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87641. this._onEndFrameObserver = null;
  87642. }
  87643. },
  87644. enumerable: true,
  87645. configurable: true
  87646. });
  87647. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87648. /**
  87649. * Gets the perf counter used for shader compilation time
  87650. */
  87651. get: function () {
  87652. return this._shaderCompilationTime;
  87653. },
  87654. enumerable: true,
  87655. configurable: true
  87656. });
  87657. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87658. /**
  87659. * Gets the shader compilation time capture status
  87660. */
  87661. get: function () {
  87662. return this._captureShaderCompilationTime;
  87663. },
  87664. /**
  87665. * Enable or disable the shader compilation time capture
  87666. */
  87667. set: function (value) {
  87668. var _this = this;
  87669. if (value === this._captureShaderCompilationTime) {
  87670. return;
  87671. }
  87672. this._captureShaderCompilationTime = value;
  87673. if (value) {
  87674. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87675. _this._shaderCompilationTime.fetchNewFrame();
  87676. _this._shaderCompilationTime.beginMonitoring();
  87677. });
  87678. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87679. _this._shaderCompilationTime.endMonitoring();
  87680. });
  87681. }
  87682. else {
  87683. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87684. this._onBeforeShaderCompilationObserver = null;
  87685. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87686. this._onAfterShaderCompilationObserver = null;
  87687. }
  87688. },
  87689. enumerable: true,
  87690. configurable: true
  87691. });
  87692. EngineInstrumentation.prototype.dispose = function () {
  87693. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87694. this._onBeginFrameObserver = null;
  87695. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87696. this._onEndFrameObserver = null;
  87697. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87698. this._onBeforeShaderCompilationObserver = null;
  87699. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87700. this._onAfterShaderCompilationObserver = null;
  87701. this.engine = null;
  87702. };
  87703. return EngineInstrumentation;
  87704. }());
  87705. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87706. })(BABYLON || (BABYLON = {}));
  87707. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87708. var BABYLON;
  87709. (function (BABYLON) {
  87710. /**
  87711. * This class can be used to get instrumentation data from a Babylon engine
  87712. */
  87713. var SceneInstrumentation = /** @class */ (function () {
  87714. function SceneInstrumentation(scene) {
  87715. var _this = this;
  87716. this.scene = scene;
  87717. this._captureActiveMeshesEvaluationTime = false;
  87718. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87719. this._captureRenderTargetsRenderTime = false;
  87720. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87721. this._captureFrameTime = false;
  87722. this._frameTime = new BABYLON.PerfCounter();
  87723. this._captureRenderTime = false;
  87724. this._renderTime = new BABYLON.PerfCounter();
  87725. this._captureInterFrameTime = false;
  87726. this._interFrameTime = new BABYLON.PerfCounter();
  87727. this._captureParticlesRenderTime = false;
  87728. this._particlesRenderTime = new BABYLON.PerfCounter();
  87729. this._captureSpritesRenderTime = false;
  87730. this._spritesRenderTime = new BABYLON.PerfCounter();
  87731. this._capturePhysicsTime = false;
  87732. this._physicsTime = new BABYLON.PerfCounter();
  87733. this._captureAnimationsTime = false;
  87734. this._animationsTime = new BABYLON.PerfCounter();
  87735. // Observers
  87736. this._onBeforeActiveMeshesEvaluationObserver = null;
  87737. this._onAfterActiveMeshesEvaluationObserver = null;
  87738. this._onBeforeRenderTargetsRenderObserver = null;
  87739. this._onAfterRenderTargetsRenderObserver = null;
  87740. this._onAfterRenderObserver = null;
  87741. this._onBeforeDrawPhaseObserver = null;
  87742. this._onAfterDrawPhaseObserver = null;
  87743. this._onBeforeAnimationsObserver = null;
  87744. this._onBeforeParticlesRenderingObserver = null;
  87745. this._onAfterParticlesRenderingObserver = null;
  87746. this._onBeforeSpritesRenderingObserver = null;
  87747. this._onAfterSpritesRenderingObserver = null;
  87748. this._onBeforePhysicsObserver = null;
  87749. this._onAfterPhysicsObserver = null;
  87750. this._onAfterAnimationsObserver = null;
  87751. // Before render
  87752. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87753. if (_this._captureActiveMeshesEvaluationTime) {
  87754. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87755. }
  87756. if (_this._captureRenderTargetsRenderTime) {
  87757. _this._renderTargetsRenderTime.fetchNewFrame();
  87758. }
  87759. if (_this._captureFrameTime) {
  87760. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87761. _this._frameTime.beginMonitoring();
  87762. }
  87763. if (_this._captureInterFrameTime) {
  87764. _this._interFrameTime.endMonitoring();
  87765. }
  87766. if (_this._captureParticlesRenderTime) {
  87767. _this._particlesRenderTime.fetchNewFrame();
  87768. }
  87769. if (_this._captureSpritesRenderTime) {
  87770. _this._spritesRenderTime.fetchNewFrame();
  87771. }
  87772. if (_this._captureAnimationsTime) {
  87773. _this._animationsTime.beginMonitoring();
  87774. }
  87775. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87776. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87777. });
  87778. // After render
  87779. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87780. if (_this._captureFrameTime) {
  87781. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87782. _this._frameTime.endMonitoring();
  87783. }
  87784. if (_this._captureRenderTime) {
  87785. _this._renderTime.endMonitoring(false);
  87786. }
  87787. if (_this._captureInterFrameTime) {
  87788. _this._interFrameTime.beginMonitoring();
  87789. }
  87790. });
  87791. }
  87792. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87793. // Properties
  87794. /**
  87795. * Gets the perf counter used for active meshes evaluation time
  87796. */
  87797. get: function () {
  87798. return this._activeMeshesEvaluationTime;
  87799. },
  87800. enumerable: true,
  87801. configurable: true
  87802. });
  87803. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87804. /**
  87805. * Gets the active meshes evaluation time capture status
  87806. */
  87807. get: function () {
  87808. return this._captureActiveMeshesEvaluationTime;
  87809. },
  87810. /**
  87811. * Enable or disable the active meshes evaluation time capture
  87812. */
  87813. set: function (value) {
  87814. var _this = this;
  87815. if (value === this._captureActiveMeshesEvaluationTime) {
  87816. return;
  87817. }
  87818. this._captureActiveMeshesEvaluationTime = value;
  87819. if (value) {
  87820. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87821. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87822. _this._activeMeshesEvaluationTime.beginMonitoring();
  87823. });
  87824. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87825. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87826. _this._activeMeshesEvaluationTime.endMonitoring();
  87827. });
  87828. }
  87829. else {
  87830. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87831. this._onBeforeActiveMeshesEvaluationObserver = null;
  87832. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87833. this._onAfterActiveMeshesEvaluationObserver = null;
  87834. }
  87835. },
  87836. enumerable: true,
  87837. configurable: true
  87838. });
  87839. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87840. /**
  87841. * Gets the perf counter used for render targets render time
  87842. */
  87843. get: function () {
  87844. return this._renderTargetsRenderTime;
  87845. },
  87846. enumerable: true,
  87847. configurable: true
  87848. });
  87849. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87850. /**
  87851. * Gets the render targets render time capture status
  87852. */
  87853. get: function () {
  87854. return this._captureRenderTargetsRenderTime;
  87855. },
  87856. /**
  87857. * Enable or disable the render targets render time capture
  87858. */
  87859. set: function (value) {
  87860. var _this = this;
  87861. if (value === this._captureRenderTargetsRenderTime) {
  87862. return;
  87863. }
  87864. this._captureRenderTargetsRenderTime = value;
  87865. if (value) {
  87866. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87867. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87868. _this._renderTargetsRenderTime.beginMonitoring();
  87869. });
  87870. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87871. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87872. _this._renderTargetsRenderTime.endMonitoring(false);
  87873. });
  87874. }
  87875. else {
  87876. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87877. this._onBeforeRenderTargetsRenderObserver = null;
  87878. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87879. this._onAfterRenderTargetsRenderObserver = null;
  87880. }
  87881. },
  87882. enumerable: true,
  87883. configurable: true
  87884. });
  87885. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87886. /**
  87887. * Gets the perf counter used for particles render time
  87888. */
  87889. get: function () {
  87890. return this._particlesRenderTime;
  87891. },
  87892. enumerable: true,
  87893. configurable: true
  87894. });
  87895. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87896. /**
  87897. * Gets the particles render time capture status
  87898. */
  87899. get: function () {
  87900. return this._captureParticlesRenderTime;
  87901. },
  87902. /**
  87903. * Enable or disable the particles render time capture
  87904. */
  87905. set: function (value) {
  87906. var _this = this;
  87907. if (value === this._captureParticlesRenderTime) {
  87908. return;
  87909. }
  87910. this._captureParticlesRenderTime = value;
  87911. if (value) {
  87912. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87913. BABYLON.Tools.StartPerformanceCounter("Particles");
  87914. _this._particlesRenderTime.beginMonitoring();
  87915. });
  87916. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87917. BABYLON.Tools.EndPerformanceCounter("Particles");
  87918. _this._particlesRenderTime.endMonitoring(false);
  87919. });
  87920. }
  87921. else {
  87922. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87923. this._onBeforeParticlesRenderingObserver = null;
  87924. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87925. this._onAfterParticlesRenderingObserver = null;
  87926. }
  87927. },
  87928. enumerable: true,
  87929. configurable: true
  87930. });
  87931. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87932. /**
  87933. * Gets the perf counter used for sprites render time
  87934. */
  87935. get: function () {
  87936. return this._spritesRenderTime;
  87937. },
  87938. enumerable: true,
  87939. configurable: true
  87940. });
  87941. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87942. /**
  87943. * Gets the sprites render time capture status
  87944. */
  87945. get: function () {
  87946. return this._captureSpritesRenderTime;
  87947. },
  87948. /**
  87949. * Enable or disable the sprites render time capture
  87950. */
  87951. set: function (value) {
  87952. var _this = this;
  87953. if (value === this._captureSpritesRenderTime) {
  87954. return;
  87955. }
  87956. this._captureSpritesRenderTime = value;
  87957. if (value) {
  87958. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87959. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87960. _this._spritesRenderTime.beginMonitoring();
  87961. });
  87962. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87963. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87964. _this._spritesRenderTime.endMonitoring(false);
  87965. });
  87966. }
  87967. else {
  87968. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87969. this._onBeforeSpritesRenderingObserver = null;
  87970. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87971. this._onAfterSpritesRenderingObserver = null;
  87972. }
  87973. },
  87974. enumerable: true,
  87975. configurable: true
  87976. });
  87977. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87978. /**
  87979. * Gets the perf counter used for physics time
  87980. */
  87981. get: function () {
  87982. return this._physicsTime;
  87983. },
  87984. enumerable: true,
  87985. configurable: true
  87986. });
  87987. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87988. /**
  87989. * Gets the physics time capture status
  87990. */
  87991. get: function () {
  87992. return this._capturePhysicsTime;
  87993. },
  87994. /**
  87995. * Enable or disable the physics time capture
  87996. */
  87997. set: function (value) {
  87998. var _this = this;
  87999. if (value === this._capturePhysicsTime) {
  88000. return;
  88001. }
  88002. this._capturePhysicsTime = value;
  88003. if (value) {
  88004. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88005. BABYLON.Tools.StartPerformanceCounter("Physics");
  88006. _this._physicsTime.beginMonitoring();
  88007. });
  88008. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88009. BABYLON.Tools.EndPerformanceCounter("Physics");
  88010. _this._physicsTime.endMonitoring();
  88011. });
  88012. }
  88013. else {
  88014. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88015. this._onBeforePhysicsObserver = null;
  88016. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88017. this._onAfterPhysicsObserver = null;
  88018. }
  88019. },
  88020. enumerable: true,
  88021. configurable: true
  88022. });
  88023. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88024. /**
  88025. * Gets the perf counter used for animations time
  88026. */
  88027. get: function () {
  88028. return this._animationsTime;
  88029. },
  88030. enumerable: true,
  88031. configurable: true
  88032. });
  88033. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88034. /**
  88035. * Gets the animations time capture status
  88036. */
  88037. get: function () {
  88038. return this._captureAnimationsTime;
  88039. },
  88040. /**
  88041. * Enable or disable the animations time capture
  88042. */
  88043. set: function (value) {
  88044. var _this = this;
  88045. if (value === this._captureAnimationsTime) {
  88046. return;
  88047. }
  88048. this._captureAnimationsTime = value;
  88049. if (value) {
  88050. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88051. _this._animationsTime.endMonitoring();
  88052. });
  88053. }
  88054. else {
  88055. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88056. this._onAfterAnimationsObserver = null;
  88057. }
  88058. },
  88059. enumerable: true,
  88060. configurable: true
  88061. });
  88062. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88063. /**
  88064. * Gets the perf counter used for frame time capture
  88065. */
  88066. get: function () {
  88067. return this._frameTime;
  88068. },
  88069. enumerable: true,
  88070. configurable: true
  88071. });
  88072. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88073. /**
  88074. * Gets the frame time capture status
  88075. */
  88076. get: function () {
  88077. return this._captureFrameTime;
  88078. },
  88079. /**
  88080. * Enable or disable the frame time capture
  88081. */
  88082. set: function (value) {
  88083. this._captureFrameTime = value;
  88084. },
  88085. enumerable: true,
  88086. configurable: true
  88087. });
  88088. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88089. /**
  88090. * Gets the perf counter used for inter-frames time capture
  88091. */
  88092. get: function () {
  88093. return this._interFrameTime;
  88094. },
  88095. enumerable: true,
  88096. configurable: true
  88097. });
  88098. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88099. /**
  88100. * Gets the inter-frames time capture status
  88101. */
  88102. get: function () {
  88103. return this._captureInterFrameTime;
  88104. },
  88105. /**
  88106. * Enable or disable the inter-frames time capture
  88107. */
  88108. set: function (value) {
  88109. this._captureInterFrameTime = value;
  88110. },
  88111. enumerable: true,
  88112. configurable: true
  88113. });
  88114. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88115. /**
  88116. * Gets the perf counter used for render time capture
  88117. */
  88118. get: function () {
  88119. return this._renderTime;
  88120. },
  88121. enumerable: true,
  88122. configurable: true
  88123. });
  88124. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88125. /**
  88126. * Gets the render time capture status
  88127. */
  88128. get: function () {
  88129. return this._captureRenderTime;
  88130. },
  88131. /**
  88132. * Enable or disable the render time capture
  88133. */
  88134. set: function (value) {
  88135. var _this = this;
  88136. if (value === this._captureRenderTime) {
  88137. return;
  88138. }
  88139. this._captureRenderTime = value;
  88140. if (value) {
  88141. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88142. _this._renderTime.beginMonitoring();
  88143. BABYLON.Tools.StartPerformanceCounter("Main render");
  88144. });
  88145. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88146. _this._renderTime.endMonitoring(false);
  88147. BABYLON.Tools.EndPerformanceCounter("Main render");
  88148. });
  88149. }
  88150. else {
  88151. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88152. this._onBeforeDrawPhaseObserver = null;
  88153. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88154. this._onAfterDrawPhaseObserver = null;
  88155. }
  88156. },
  88157. enumerable: true,
  88158. configurable: true
  88159. });
  88160. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88161. /**
  88162. * Gets the perf counter used for draw calls
  88163. */
  88164. get: function () {
  88165. return this.scene.getEngine()._drawCalls;
  88166. },
  88167. enumerable: true,
  88168. configurable: true
  88169. });
  88170. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88171. /**
  88172. * Gets the perf counter used for texture collisions
  88173. */
  88174. get: function () {
  88175. return this.scene.getEngine()._textureCollisions;
  88176. },
  88177. enumerable: true,
  88178. configurable: true
  88179. });
  88180. SceneInstrumentation.prototype.dispose = function () {
  88181. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88182. this._onAfterRenderObserver = null;
  88183. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88184. this._onBeforeActiveMeshesEvaluationObserver = null;
  88185. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88186. this._onAfterActiveMeshesEvaluationObserver = null;
  88187. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88188. this._onBeforeRenderTargetsRenderObserver = null;
  88189. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88190. this._onAfterRenderTargetsRenderObserver = null;
  88191. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88192. this._onBeforeAnimationsObserver = null;
  88193. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88194. this._onBeforeParticlesRenderingObserver = null;
  88195. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88196. this._onAfterParticlesRenderingObserver = null;
  88197. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88198. this._onBeforeSpritesRenderingObserver = null;
  88199. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88200. this._onAfterSpritesRenderingObserver = null;
  88201. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88202. this._onBeforeDrawPhaseObserver = null;
  88203. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88204. this._onAfterDrawPhaseObserver = null;
  88205. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88206. this._onBeforePhysicsObserver = null;
  88207. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88208. this._onAfterPhysicsObserver = null;
  88209. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88210. this._onAfterAnimationsObserver = null;
  88211. this.scene = null;
  88212. };
  88213. return SceneInstrumentation;
  88214. }());
  88215. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88216. })(BABYLON || (BABYLON = {}));
  88217. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88218. var BABYLON;
  88219. (function (BABYLON) {
  88220. var _TimeToken = /** @class */ (function () {
  88221. function _TimeToken() {
  88222. this._timeElapsedQueryEnded = false;
  88223. }
  88224. return _TimeToken;
  88225. }());
  88226. BABYLON._TimeToken = _TimeToken;
  88227. })(BABYLON || (BABYLON = {}));
  88228. //# sourceMappingURL=babylon.timeToken.js.map
  88229. var BABYLON;
  88230. (function (BABYLON) {
  88231. /**
  88232. * Background material defines definition.
  88233. * @ignore Mainly internal Use
  88234. */
  88235. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88236. __extends(BackgroundMaterialDefines, _super);
  88237. /**
  88238. * Constructor of the defines.
  88239. */
  88240. function BackgroundMaterialDefines() {
  88241. var _this = _super.call(this) || this;
  88242. /**
  88243. * True if the diffuse texture is in use.
  88244. */
  88245. _this.DIFFUSE = false;
  88246. /**
  88247. * The direct UV channel to use.
  88248. */
  88249. _this.DIFFUSEDIRECTUV = 0;
  88250. /**
  88251. * True if the diffuse texture is in gamma space.
  88252. */
  88253. _this.GAMMADIFFUSE = false;
  88254. /**
  88255. * True if the diffuse texture has opacity in the alpha channel.
  88256. */
  88257. _this.DIFFUSEHASALPHA = false;
  88258. /**
  88259. * True if you want the material to fade to transparent at grazing angle.
  88260. */
  88261. _this.OPACITYFRESNEL = false;
  88262. /**
  88263. * True if an extra blur needs to be added in the reflection.
  88264. */
  88265. _this.REFLECTIONBLUR = false;
  88266. /**
  88267. * True if you want the material to fade to reflection at grazing angle.
  88268. */
  88269. _this.REFLECTIONFRESNEL = false;
  88270. /**
  88271. * True if you want the material to falloff as far as you move away from the scene center.
  88272. */
  88273. _this.REFLECTIONFALLOFF = false;
  88274. /**
  88275. * False if the current Webgl implementation does not support the texture lod extension.
  88276. */
  88277. _this.TEXTURELODSUPPORT = false;
  88278. /**
  88279. * True to ensure the data are premultiplied.
  88280. */
  88281. _this.PREMULTIPLYALPHA = false;
  88282. /**
  88283. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88284. */
  88285. _this.USERGBCOLOR = false;
  88286. /**
  88287. * True to add noise in order to reduce the banding effect.
  88288. */
  88289. _this.NOISE = false;
  88290. /**
  88291. * is the reflection texture in BGR color scheme?
  88292. * Mainly used to solve a bug in ios10 video tag
  88293. */
  88294. _this.REFLECTIONBGR = false;
  88295. _this.IMAGEPROCESSING = false;
  88296. _this.VIGNETTE = false;
  88297. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88298. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88299. _this.TONEMAPPING = false;
  88300. _this.CONTRAST = false;
  88301. _this.COLORCURVES = false;
  88302. _this.COLORGRADING = false;
  88303. _this.COLORGRADING3D = false;
  88304. _this.SAMPLER3DGREENDEPTH = false;
  88305. _this.SAMPLER3DBGRMAP = false;
  88306. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88307. _this.EXPOSURE = false;
  88308. _this.GRAIN = false;
  88309. // Reflection.
  88310. _this.REFLECTION = false;
  88311. _this.REFLECTIONMAP_3D = false;
  88312. _this.REFLECTIONMAP_SPHERICAL = false;
  88313. _this.REFLECTIONMAP_PLANAR = false;
  88314. _this.REFLECTIONMAP_CUBIC = false;
  88315. _this.REFLECTIONMAP_PROJECTION = false;
  88316. _this.REFLECTIONMAP_SKYBOX = false;
  88317. _this.REFLECTIONMAP_EXPLICIT = false;
  88318. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88319. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88320. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88321. _this.INVERTCUBICMAP = false;
  88322. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88323. _this.LODINREFLECTIONALPHA = false;
  88324. _this.GAMMAREFLECTION = false;
  88325. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88326. // Default BJS.
  88327. _this.MAINUV1 = false;
  88328. _this.MAINUV2 = false;
  88329. _this.UV1 = false;
  88330. _this.UV2 = false;
  88331. _this.CLIPPLANE = false;
  88332. _this.POINTSIZE = false;
  88333. _this.FOG = false;
  88334. _this.NORMAL = false;
  88335. _this.NUM_BONE_INFLUENCERS = 0;
  88336. _this.BonesPerMesh = 0;
  88337. _this.INSTANCES = false;
  88338. _this.SHADOWFLOAT = false;
  88339. _this.rebuild();
  88340. return _this;
  88341. }
  88342. return BackgroundMaterialDefines;
  88343. }(BABYLON.MaterialDefines));
  88344. /**
  88345. * Background material used to create an efficient environement around your scene.
  88346. */
  88347. var BackgroundMaterial = /** @class */ (function (_super) {
  88348. __extends(BackgroundMaterial, _super);
  88349. /**
  88350. * Instantiates a Background Material in the given scene
  88351. * @param name The friendly name of the material
  88352. * @param scene The scene to add the material to
  88353. */
  88354. function BackgroundMaterial(name, scene) {
  88355. var _this = _super.call(this, name, scene) || this;
  88356. /**
  88357. * Key light Color (multiply against the R channel of the environement texture)
  88358. */
  88359. _this.primaryColor = BABYLON.Color3.White();
  88360. /**
  88361. * Key light Level (allowing HDR output of the background)
  88362. */
  88363. _this.primaryLevel = 1;
  88364. /**
  88365. * Secondary light Color (multiply against the G channel of the environement texture)
  88366. */
  88367. _this.secondaryColor = BABYLON.Color3.Gray();
  88368. /**
  88369. * Secondary light Level (allowing HDR output of the background)
  88370. */
  88371. _this.secondaryLevel = 1;
  88372. /**
  88373. * Tertiary light Color (multiply against the B channel of the environement texture)
  88374. */
  88375. _this.tertiaryColor = BABYLON.Color3.Black();
  88376. /**
  88377. * Tertiary light Level (allowing HDR output of the background)
  88378. */
  88379. _this.tertiaryLevel = 1;
  88380. /**
  88381. * Reflection Texture used in the material.
  88382. * Should be author in a specific way for the best result (refer to the documentation).
  88383. */
  88384. _this.reflectionTexture = null;
  88385. /**
  88386. * Reflection Texture level of blur.
  88387. *
  88388. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88389. * texture twice.
  88390. */
  88391. _this.reflectionBlur = 0;
  88392. /**
  88393. * Diffuse Texture used in the material.
  88394. * Should be author in a specific way for the best result (refer to the documentation).
  88395. */
  88396. _this.diffuseTexture = null;
  88397. _this._shadowLights = null;
  88398. /**
  88399. * Specify the list of lights casting shadow on the material.
  88400. * All scene shadow lights will be included if null.
  88401. */
  88402. _this.shadowLights = null;
  88403. /**
  88404. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88405. * soft lighting on the background.
  88406. */
  88407. _this.shadowBlurScale = 1;
  88408. /**
  88409. * Helps adjusting the shadow to a softer level if required.
  88410. * 0 means black shadows and 1 means no shadows.
  88411. */
  88412. _this.shadowLevel = 0;
  88413. /**
  88414. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88415. * It is usually zero but might be interesting to modify according to your setup.
  88416. */
  88417. _this.sceneCenter = BABYLON.Vector3.Zero();
  88418. /**
  88419. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88420. * This helps ensuring a nice transition when the camera goes under the ground.
  88421. */
  88422. _this.opacityFresnel = true;
  88423. /**
  88424. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88425. * This helps adding a mirror texture on the ground.
  88426. */
  88427. _this.reflectionFresnel = false;
  88428. /**
  88429. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88430. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88431. */
  88432. _this.reflectionFalloffDistance = 0.0;
  88433. /**
  88434. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88435. */
  88436. _this.reflectionAmount = 1.0;
  88437. /**
  88438. * This specifies the weight of the reflection at grazing angle.
  88439. */
  88440. _this.reflectionReflectance0 = 0.05;
  88441. /**
  88442. * This specifies the weight of the reflection at a perpendicular point of view.
  88443. */
  88444. _this.reflectionReflectance90 = 0.5;
  88445. /**
  88446. * Helps to directly use the maps channels instead of their level.
  88447. */
  88448. _this.useRGBColor = true;
  88449. /**
  88450. * This helps reducing the banding effect that could occur on the background.
  88451. */
  88452. _this.enableNoise = false;
  88453. _this._fovMultiplier = 1.0;
  88454. /**
  88455. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88456. * @type {boolean}
  88457. */
  88458. _this.useEquirectangularFOV = false;
  88459. _this._maxSimultaneousLights = 4;
  88460. /**
  88461. * Number of Simultaneous lights allowed on the material.
  88462. */
  88463. _this.maxSimultaneousLights = 4;
  88464. /**
  88465. * Keep track of the image processing observer to allow dispose and replace.
  88466. */
  88467. _this._imageProcessingObserver = null;
  88468. /**
  88469. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88470. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88471. */
  88472. _this.switchToBGR = false;
  88473. // Temp values kept as cache in the material.
  88474. _this._renderTargets = new BABYLON.SmartArray(16);
  88475. _this._reflectionControls = BABYLON.Vector4.Zero();
  88476. // Setup the default processing configuration to the scene.
  88477. _this._attachImageProcessingConfiguration(null);
  88478. _this.getRenderTargetTextures = function () {
  88479. _this._renderTargets.reset();
  88480. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88481. _this._renderTargets.push(_this._diffuseTexture);
  88482. }
  88483. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88484. _this._renderTargets.push(_this._reflectionTexture);
  88485. }
  88486. return _this._renderTargets;
  88487. };
  88488. return _this;
  88489. }
  88490. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88491. /**
  88492. * Sets the reflection reflectance fresnel values according to the default standard
  88493. * empirically know to work well :-)
  88494. */
  88495. set: function (value) {
  88496. var reflectionWeight = value;
  88497. if (reflectionWeight < 0.5) {
  88498. reflectionWeight = reflectionWeight * 2.0;
  88499. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88500. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88501. }
  88502. else {
  88503. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88504. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88505. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88506. }
  88507. },
  88508. enumerable: true,
  88509. configurable: true
  88510. });
  88511. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88512. /**
  88513. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88514. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88515. * Recommended to be keep at 1.0 except for special cases.
  88516. */
  88517. get: function () {
  88518. return this._fovMultiplier;
  88519. },
  88520. set: function (value) {
  88521. if (isNaN(value)) {
  88522. value = 1.0;
  88523. }
  88524. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88525. },
  88526. enumerable: true,
  88527. configurable: true
  88528. });
  88529. /**
  88530. * Attaches a new image processing configuration to the PBR Material.
  88531. * @param configuration (if null the scene configuration will be use)
  88532. */
  88533. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88534. var _this = this;
  88535. if (configuration === this._imageProcessingConfiguration) {
  88536. return;
  88537. }
  88538. // Detaches observer.
  88539. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88540. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88541. }
  88542. // Pick the scene configuration if needed.
  88543. if (!configuration) {
  88544. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88545. }
  88546. else {
  88547. this._imageProcessingConfiguration = configuration;
  88548. }
  88549. // Attaches observer.
  88550. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88551. _this._markAllSubMeshesAsImageProcessingDirty();
  88552. });
  88553. };
  88554. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88555. /**
  88556. * Gets the image processing configuration used either in this material.
  88557. */
  88558. get: function () {
  88559. return this._imageProcessingConfiguration;
  88560. },
  88561. /**
  88562. * Sets the Default image processing configuration used either in the this material.
  88563. *
  88564. * If sets to null, the scene one is in use.
  88565. */
  88566. set: function (value) {
  88567. this._attachImageProcessingConfiguration(value);
  88568. // Ensure the effect will be rebuilt.
  88569. this._markAllSubMeshesAsTexturesDirty();
  88570. },
  88571. enumerable: true,
  88572. configurable: true
  88573. });
  88574. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88575. /**
  88576. * Gets wether the color curves effect is enabled.
  88577. */
  88578. get: function () {
  88579. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88580. },
  88581. /**
  88582. * Sets wether the color curves effect is enabled.
  88583. */
  88584. set: function (value) {
  88585. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88586. },
  88587. enumerable: true,
  88588. configurable: true
  88589. });
  88590. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88591. /**
  88592. * Gets wether the color grading effect is enabled.
  88593. */
  88594. get: function () {
  88595. return this.imageProcessingConfiguration.colorGradingEnabled;
  88596. },
  88597. /**
  88598. * Gets wether the color grading effect is enabled.
  88599. */
  88600. set: function (value) {
  88601. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88602. },
  88603. enumerable: true,
  88604. configurable: true
  88605. });
  88606. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88607. /**
  88608. * Gets wether tonemapping is enabled or not.
  88609. */
  88610. get: function () {
  88611. return this._imageProcessingConfiguration.toneMappingEnabled;
  88612. },
  88613. /**
  88614. * Sets wether tonemapping is enabled or not
  88615. */
  88616. set: function (value) {
  88617. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88618. },
  88619. enumerable: true,
  88620. configurable: true
  88621. });
  88622. ;
  88623. ;
  88624. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88625. /**
  88626. * The camera exposure used on this material.
  88627. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88628. * This corresponds to a photographic exposure.
  88629. */
  88630. get: function () {
  88631. return this._imageProcessingConfiguration.exposure;
  88632. },
  88633. /**
  88634. * The camera exposure used on this material.
  88635. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88636. * This corresponds to a photographic exposure.
  88637. */
  88638. set: function (value) {
  88639. this._imageProcessingConfiguration.exposure = value;
  88640. },
  88641. enumerable: true,
  88642. configurable: true
  88643. });
  88644. ;
  88645. ;
  88646. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88647. /**
  88648. * Gets The camera contrast used on this material.
  88649. */
  88650. get: function () {
  88651. return this._imageProcessingConfiguration.contrast;
  88652. },
  88653. /**
  88654. * Sets The camera contrast used on this material.
  88655. */
  88656. set: function (value) {
  88657. this._imageProcessingConfiguration.contrast = value;
  88658. },
  88659. enumerable: true,
  88660. configurable: true
  88661. });
  88662. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88663. /**
  88664. * Gets the Color Grading 2D Lookup Texture.
  88665. */
  88666. get: function () {
  88667. return this._imageProcessingConfiguration.colorGradingTexture;
  88668. },
  88669. /**
  88670. * Sets the Color Grading 2D Lookup Texture.
  88671. */
  88672. set: function (value) {
  88673. this.imageProcessingConfiguration.colorGradingTexture = value;
  88674. },
  88675. enumerable: true,
  88676. configurable: true
  88677. });
  88678. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88679. /**
  88680. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88681. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88682. * 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;
  88683. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88684. */
  88685. get: function () {
  88686. return this.imageProcessingConfiguration.colorCurves;
  88687. },
  88688. /**
  88689. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88690. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88691. * 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;
  88692. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88693. */
  88694. set: function (value) {
  88695. this.imageProcessingConfiguration.colorCurves = value;
  88696. },
  88697. enumerable: true,
  88698. configurable: true
  88699. });
  88700. /**
  88701. * The entire material has been created in order to prevent overdraw.
  88702. * @returns false
  88703. */
  88704. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88705. return true;
  88706. };
  88707. /**
  88708. * The entire material has been created in order to prevent overdraw.
  88709. * @returns true if blending is enable
  88710. */
  88711. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88712. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88713. };
  88714. /**
  88715. * Checks wether the material is ready to be rendered for a given mesh.
  88716. * @param mesh The mesh to render
  88717. * @param subMesh The submesh to check against
  88718. * @param useInstances Specify wether or not the material is used with instances
  88719. * @returns true if all the dependencies are ready (Textures, Effects...)
  88720. */
  88721. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88722. var _this = this;
  88723. if (useInstances === void 0) { useInstances = false; }
  88724. if (subMesh.effect && this.isFrozen) {
  88725. if (this._wasPreviouslyReady) {
  88726. return true;
  88727. }
  88728. }
  88729. if (!subMesh._materialDefines) {
  88730. subMesh._materialDefines = new BackgroundMaterialDefines();
  88731. }
  88732. var scene = this.getScene();
  88733. var defines = subMesh._materialDefines;
  88734. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88735. if (defines._renderId === scene.getRenderId()) {
  88736. return true;
  88737. }
  88738. }
  88739. var engine = scene.getEngine();
  88740. // Lights
  88741. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88742. defines._needNormals = true;
  88743. // Textures
  88744. if (defines._areTexturesDirty) {
  88745. defines._needUVs = false;
  88746. if (scene.texturesEnabled) {
  88747. if (scene.getEngine().getCaps().textureLOD) {
  88748. defines.TEXTURELODSUPPORT = true;
  88749. }
  88750. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88751. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88752. return false;
  88753. }
  88754. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88755. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88756. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88757. defines.OPACITYFRESNEL = this._opacityFresnel;
  88758. }
  88759. else {
  88760. defines.DIFFUSE = false;
  88761. defines.DIFFUSEHASALPHA = false;
  88762. defines.GAMMADIFFUSE = false;
  88763. defines.OPACITYFRESNEL = false;
  88764. }
  88765. var reflectionTexture = this._reflectionTexture;
  88766. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88767. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88768. return false;
  88769. }
  88770. defines.REFLECTION = true;
  88771. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88772. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88773. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88774. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88775. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88776. defines.REFLECTIONBGR = this.switchToBGR;
  88777. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88778. defines.INVERTCUBICMAP = true;
  88779. }
  88780. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88781. switch (reflectionTexture.coordinatesMode) {
  88782. case BABYLON.Texture.CUBIC_MODE:
  88783. case BABYLON.Texture.INVCUBIC_MODE:
  88784. defines.REFLECTIONMAP_CUBIC = true;
  88785. break;
  88786. case BABYLON.Texture.EXPLICIT_MODE:
  88787. defines.REFLECTIONMAP_EXPLICIT = true;
  88788. break;
  88789. case BABYLON.Texture.PLANAR_MODE:
  88790. defines.REFLECTIONMAP_PLANAR = true;
  88791. break;
  88792. case BABYLON.Texture.PROJECTION_MODE:
  88793. defines.REFLECTIONMAP_PROJECTION = true;
  88794. break;
  88795. case BABYLON.Texture.SKYBOX_MODE:
  88796. defines.REFLECTIONMAP_SKYBOX = true;
  88797. break;
  88798. case BABYLON.Texture.SPHERICAL_MODE:
  88799. defines.REFLECTIONMAP_SPHERICAL = true;
  88800. break;
  88801. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88802. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88803. break;
  88804. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88805. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88806. break;
  88807. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88808. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88809. break;
  88810. }
  88811. if (this.reflectionFresnel) {
  88812. defines.REFLECTIONFRESNEL = true;
  88813. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88814. this._reflectionControls.x = this.reflectionAmount;
  88815. this._reflectionControls.y = this.reflectionReflectance0;
  88816. this._reflectionControls.z = this.reflectionReflectance90;
  88817. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88818. }
  88819. else {
  88820. defines.REFLECTIONFRESNEL = false;
  88821. defines.REFLECTIONFALLOFF = false;
  88822. }
  88823. }
  88824. else {
  88825. defines.REFLECTION = false;
  88826. defines.REFLECTIONFALLOFF = false;
  88827. defines.REFLECTIONBLUR = false;
  88828. defines.REFLECTIONMAP_3D = false;
  88829. defines.REFLECTIONMAP_SPHERICAL = false;
  88830. defines.REFLECTIONMAP_PLANAR = false;
  88831. defines.REFLECTIONMAP_CUBIC = false;
  88832. defines.REFLECTIONMAP_PROJECTION = false;
  88833. defines.REFLECTIONMAP_SKYBOX = false;
  88834. defines.REFLECTIONMAP_EXPLICIT = false;
  88835. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88836. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88837. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88838. defines.INVERTCUBICMAP = false;
  88839. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88840. defines.LODINREFLECTIONALPHA = false;
  88841. defines.GAMMAREFLECTION = false;
  88842. }
  88843. }
  88844. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88845. defines.USERGBCOLOR = this._useRGBColor;
  88846. defines.NOISE = this._enableNoise;
  88847. }
  88848. if (defines._areImageProcessingDirty) {
  88849. if (!this._imageProcessingConfiguration.isReady()) {
  88850. return false;
  88851. }
  88852. this._imageProcessingConfiguration.prepareDefines(defines);
  88853. }
  88854. // Misc.
  88855. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88856. // Values that need to be evaluated on every frame
  88857. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88858. // Attribs
  88859. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88860. if (mesh) {
  88861. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88862. mesh.createNormals(true);
  88863. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88864. }
  88865. }
  88866. }
  88867. // Get correct effect
  88868. if (defines.isDirty) {
  88869. defines.markAsProcessed();
  88870. scene.resetCachedMaterial();
  88871. // Fallbacks
  88872. var fallbacks = new BABYLON.EffectFallbacks();
  88873. if (defines.FOG) {
  88874. fallbacks.addFallback(0, "FOG");
  88875. }
  88876. if (defines.POINTSIZE) {
  88877. fallbacks.addFallback(1, "POINTSIZE");
  88878. }
  88879. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88880. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88881. fallbacks.addCPUSkinningFallback(0, mesh);
  88882. }
  88883. //Attributes
  88884. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88885. if (defines.NORMAL) {
  88886. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88887. }
  88888. if (defines.UV1) {
  88889. attribs.push(BABYLON.VertexBuffer.UVKind);
  88890. }
  88891. if (defines.UV2) {
  88892. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88893. }
  88894. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88895. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88896. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88897. "vFogInfos", "vFogColor", "pointSize",
  88898. "vClipPlane", "mBones",
  88899. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88900. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88901. "shadowLevel", "alpha",
  88902. "vBackgroundCenter", "vReflectionControl",
  88903. "vDiffuseInfos", "diffuseMatrix",
  88904. ];
  88905. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88906. var uniformBuffers = ["Material", "Scene"];
  88907. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88908. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88909. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88910. uniformsNames: uniforms,
  88911. uniformBuffersNames: uniformBuffers,
  88912. samplers: samplers,
  88913. defines: defines,
  88914. maxSimultaneousLights: this._maxSimultaneousLights
  88915. });
  88916. var onCompiled = function (effect) {
  88917. if (_this.onCompiled) {
  88918. _this.onCompiled(effect);
  88919. }
  88920. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88921. };
  88922. var join = defines.toString();
  88923. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88924. attributes: attribs,
  88925. uniformsNames: uniforms,
  88926. uniformBuffersNames: uniformBuffers,
  88927. samplers: samplers,
  88928. defines: join,
  88929. fallbacks: fallbacks,
  88930. onCompiled: onCompiled,
  88931. onError: this.onError,
  88932. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88933. }, engine), defines);
  88934. this.buildUniformLayout();
  88935. }
  88936. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88937. return false;
  88938. }
  88939. defines._renderId = scene.getRenderId();
  88940. this._wasPreviouslyReady = true;
  88941. return true;
  88942. };
  88943. /**
  88944. * Build the uniform buffer used in the material.
  88945. */
  88946. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88947. // Order is important !
  88948. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88949. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88950. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88951. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88952. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88953. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88954. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88955. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88956. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88957. this._uniformBuffer.addUniform("pointSize", 1);
  88958. this._uniformBuffer.addUniform("shadowLevel", 1);
  88959. this._uniformBuffer.addUniform("alpha", 1);
  88960. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88961. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88962. this._uniformBuffer.create();
  88963. };
  88964. /**
  88965. * Unbind the material.
  88966. */
  88967. BackgroundMaterial.prototype.unbind = function () {
  88968. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88969. this._uniformBuffer.setTexture("diffuseSampler", null);
  88970. }
  88971. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88972. this._uniformBuffer.setTexture("reflectionSampler", null);
  88973. }
  88974. _super.prototype.unbind.call(this);
  88975. };
  88976. /**
  88977. * Bind only the world matrix to the material.
  88978. * @param world The world matrix to bind.
  88979. */
  88980. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88981. this._activeEffect.setMatrix("world", world);
  88982. };
  88983. /**
  88984. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88985. * @param world The world matrix to bind.
  88986. * @param subMesh The submesh to bind for.
  88987. */
  88988. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88989. var scene = this.getScene();
  88990. var defines = subMesh._materialDefines;
  88991. if (!defines) {
  88992. return;
  88993. }
  88994. var effect = subMesh.effect;
  88995. if (!effect) {
  88996. return;
  88997. }
  88998. this._activeEffect = effect;
  88999. // Matrices
  89000. this.bindOnlyWorldMatrix(world);
  89001. // Bones
  89002. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89003. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89004. if (mustRebind) {
  89005. this._uniformBuffer.bindToEffect(effect, "Material");
  89006. this.bindViewProjection(effect);
  89007. var reflectionTexture = this._reflectionTexture;
  89008. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89009. // Texture uniforms
  89010. if (scene.texturesEnabled) {
  89011. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89012. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89013. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89014. }
  89015. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89016. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89017. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89018. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89019. }
  89020. }
  89021. if (this.shadowLevel > 0) {
  89022. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89023. }
  89024. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89025. // Point size
  89026. if (this.pointsCloud) {
  89027. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89028. }
  89029. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89030. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89031. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89032. }
  89033. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89034. // Textures
  89035. if (scene.texturesEnabled) {
  89036. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89037. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89038. }
  89039. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89040. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89041. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89042. }
  89043. else if (!defines.REFLECTIONBLUR) {
  89044. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89045. }
  89046. else {
  89047. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89048. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89049. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89050. }
  89051. if (defines.REFLECTIONFRESNEL) {
  89052. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89053. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89054. }
  89055. }
  89056. }
  89057. // Clip plane
  89058. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89059. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89060. }
  89061. if (mustRebind || !this.isFrozen) {
  89062. if (scene.lightsEnabled) {
  89063. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89064. }
  89065. // View
  89066. this.bindView(effect);
  89067. // Fog
  89068. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89069. // image processing
  89070. this._imageProcessingConfiguration.bind(this._activeEffect);
  89071. }
  89072. this._uniformBuffer.update();
  89073. this._afterBind(mesh);
  89074. };
  89075. /**
  89076. * Dispose the material.
  89077. * @param forceDisposeEffect Force disposal of the associated effect.
  89078. * @param forceDisposeTextures Force disposal of the associated textures.
  89079. */
  89080. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89081. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89082. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89083. if (forceDisposeTextures) {
  89084. if (this.diffuseTexture) {
  89085. this.diffuseTexture.dispose();
  89086. }
  89087. if (this.reflectionTexture) {
  89088. this.reflectionTexture.dispose();
  89089. }
  89090. }
  89091. this._renderTargets.dispose();
  89092. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89093. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89094. }
  89095. _super.prototype.dispose.call(this, forceDisposeEffect);
  89096. };
  89097. /**
  89098. * Clones the material.
  89099. * @param name The cloned name.
  89100. * @returns The cloned material.
  89101. */
  89102. BackgroundMaterial.prototype.clone = function (name) {
  89103. var _this = this;
  89104. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89105. };
  89106. /**
  89107. * Serializes the current material to its JSON representation.
  89108. * @returns The JSON representation.
  89109. */
  89110. BackgroundMaterial.prototype.serialize = function () {
  89111. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89112. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89113. return serializationObject;
  89114. };
  89115. /**
  89116. * Gets the class name of the material
  89117. * @returns "BackgroundMaterial"
  89118. */
  89119. BackgroundMaterial.prototype.getClassName = function () {
  89120. return "BackgroundMaterial";
  89121. };
  89122. /**
  89123. * Parse a JSON input to create back a background material.
  89124. * @param source The JSON data to parse
  89125. * @param scene The scene to create the parsed material in
  89126. * @param rootUrl The root url of the assets the material depends upon
  89127. * @returns the instantiated BackgroundMaterial.
  89128. */
  89129. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89130. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89131. };
  89132. /**
  89133. * Standard reflectance value at parallel view angle.
  89134. */
  89135. BackgroundMaterial.StandardReflectance0 = 0.05;
  89136. /**
  89137. * Standard reflectance value at grazing angle.
  89138. */
  89139. BackgroundMaterial.StandardReflectance90 = 0.5;
  89140. __decorate([
  89141. BABYLON.serializeAsColor3()
  89142. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89143. __decorate([
  89144. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89145. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89146. __decorate([
  89147. BABYLON.serialize()
  89148. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89149. __decorate([
  89150. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89151. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89152. __decorate([
  89153. BABYLON.serializeAsColor3()
  89154. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89155. __decorate([
  89156. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89157. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89158. __decorate([
  89159. BABYLON.serialize()
  89160. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89161. __decorate([
  89162. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89163. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89164. __decorate([
  89165. BABYLON.serializeAsColor3()
  89166. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89167. __decorate([
  89168. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89169. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89170. __decorate([
  89171. BABYLON.serialize()
  89172. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89173. __decorate([
  89174. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89175. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89176. __decorate([
  89177. BABYLON.serializeAsTexture()
  89178. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89179. __decorate([
  89180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89181. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89182. __decorate([
  89183. BABYLON.serialize()
  89184. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89185. __decorate([
  89186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89187. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89188. __decorate([
  89189. BABYLON.serializeAsTexture()
  89190. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89191. __decorate([
  89192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89193. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89194. __decorate([
  89195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89196. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89197. __decorate([
  89198. BABYLON.serialize()
  89199. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89200. __decorate([
  89201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89202. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89203. __decorate([
  89204. BABYLON.serialize()
  89205. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89206. __decorate([
  89207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89208. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89209. __decorate([
  89210. BABYLON.serializeAsVector3()
  89211. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89212. __decorate([
  89213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89214. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89215. __decorate([
  89216. BABYLON.serialize()
  89217. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89218. __decorate([
  89219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89220. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89221. __decorate([
  89222. BABYLON.serialize()
  89223. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89224. __decorate([
  89225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89226. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89227. __decorate([
  89228. BABYLON.serialize()
  89229. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89230. __decorate([
  89231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89232. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89233. __decorate([
  89234. BABYLON.serialize()
  89235. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89236. __decorate([
  89237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89238. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89239. __decorate([
  89240. BABYLON.serialize()
  89241. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89242. __decorate([
  89243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89244. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89245. __decorate([
  89246. BABYLON.serialize()
  89247. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89248. __decorate([
  89249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89250. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89251. __decorate([
  89252. BABYLON.serialize()
  89253. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89254. __decorate([
  89255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89256. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89257. __decorate([
  89258. BABYLON.serialize()
  89259. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89260. __decorate([
  89261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89262. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89263. __decorate([
  89264. BABYLON.serialize()
  89265. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89266. __decorate([
  89267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89268. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89269. __decorate([
  89270. BABYLON.serializeAsImageProcessingConfiguration()
  89271. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89272. return BackgroundMaterial;
  89273. }(BABYLON.PushMaterial));
  89274. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89275. })(BABYLON || (BABYLON = {}));
  89276. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89277. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89278. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89279. s = arguments[i];
  89280. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89281. t[p] = s[p];
  89282. }
  89283. return t;
  89284. };
  89285. var BABYLON;
  89286. (function (BABYLON) {
  89287. /**
  89288. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89289. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89290. * It also helps with the default setup of your imageProcessing configuration.
  89291. */
  89292. var EnvironmentHelper = /** @class */ (function () {
  89293. /**
  89294. * constructor
  89295. * @param options
  89296. * @param scene The scene to add the material to
  89297. */
  89298. function EnvironmentHelper(options, scene) {
  89299. var _this = this;
  89300. this._errorHandler = function (message, exception) {
  89301. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  89302. };
  89303. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89304. this._scene = scene;
  89305. this.onErrorObservable = new BABYLON.Observable();
  89306. this._setupBackground();
  89307. this._setupImageProcessing();
  89308. }
  89309. /**
  89310. * Creates the default options for the helper.
  89311. */
  89312. EnvironmentHelper._getDefaultOptions = function () {
  89313. return {
  89314. createGround: true,
  89315. groundSize: 15,
  89316. groundTexture: this._groundTextureCDNUrl,
  89317. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89318. groundOpacity: 0.9,
  89319. enableGroundShadow: true,
  89320. groundShadowLevel: 0.5,
  89321. enableGroundMirror: false,
  89322. groundMirrorSizeRatio: 0.3,
  89323. groundMirrorBlurKernel: 64,
  89324. groundMirrorAmount: 1,
  89325. groundMirrorFresnelWeight: 1,
  89326. groundMirrorFallOffDistance: 0,
  89327. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89328. groundYBias: 0.00001,
  89329. createSkybox: true,
  89330. skyboxSize: 20,
  89331. skyboxTexture: this._skyboxTextureCDNUrl,
  89332. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89333. backgroundYRotation: 0,
  89334. sizeAuto: true,
  89335. rootPosition: BABYLON.Vector3.Zero(),
  89336. setupImageProcessing: true,
  89337. environmentTexture: this._environmentTextureCDNUrl,
  89338. cameraExposure: 0.8,
  89339. cameraContrast: 1.2,
  89340. toneMappingEnabled: true,
  89341. };
  89342. };
  89343. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89344. /**
  89345. * Gets the root mesh created by the helper.
  89346. */
  89347. get: function () {
  89348. return this._rootMesh;
  89349. },
  89350. enumerable: true,
  89351. configurable: true
  89352. });
  89353. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89354. /**
  89355. * Gets the skybox created by the helper.
  89356. */
  89357. get: function () {
  89358. return this._skybox;
  89359. },
  89360. enumerable: true,
  89361. configurable: true
  89362. });
  89363. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89364. /**
  89365. * Gets the skybox texture created by the helper.
  89366. */
  89367. get: function () {
  89368. return this._skyboxTexture;
  89369. },
  89370. enumerable: true,
  89371. configurable: true
  89372. });
  89373. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89374. /**
  89375. * Gets the skybox material created by the helper.
  89376. */
  89377. get: function () {
  89378. return this._skyboxMaterial;
  89379. },
  89380. enumerable: true,
  89381. configurable: true
  89382. });
  89383. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89384. /**
  89385. * Gets the ground mesh created by the helper.
  89386. */
  89387. get: function () {
  89388. return this._ground;
  89389. },
  89390. enumerable: true,
  89391. configurable: true
  89392. });
  89393. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89394. /**
  89395. * Gets the ground texture created by the helper.
  89396. */
  89397. get: function () {
  89398. return this._groundTexture;
  89399. },
  89400. enumerable: true,
  89401. configurable: true
  89402. });
  89403. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89404. /**
  89405. * Gets the ground mirror created by the helper.
  89406. */
  89407. get: function () {
  89408. return this._groundMirror;
  89409. },
  89410. enumerable: true,
  89411. configurable: true
  89412. });
  89413. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89414. /**
  89415. * Gets the ground mirror render list to helps pushing the meshes
  89416. * you wish in the ground reflection.
  89417. */
  89418. get: function () {
  89419. if (this._groundMirror) {
  89420. return this._groundMirror.renderList;
  89421. }
  89422. return null;
  89423. },
  89424. enumerable: true,
  89425. configurable: true
  89426. });
  89427. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89428. /**
  89429. * Gets the ground material created by the helper.
  89430. */
  89431. get: function () {
  89432. return this._groundMaterial;
  89433. },
  89434. enumerable: true,
  89435. configurable: true
  89436. });
  89437. /**
  89438. * Updates the background according to the new options
  89439. * @param options
  89440. */
  89441. EnvironmentHelper.prototype.updateOptions = function (options) {
  89442. var newOptions = __assign({}, this._options, options);
  89443. if (this._ground && !newOptions.createGround) {
  89444. this._ground.dispose();
  89445. this._ground = null;
  89446. }
  89447. if (this._groundMaterial && !newOptions.createGround) {
  89448. this._groundMaterial.dispose();
  89449. this._groundMaterial = null;
  89450. }
  89451. if (this._groundTexture) {
  89452. if (this._options.groundTexture != newOptions.groundTexture) {
  89453. this._groundTexture.dispose();
  89454. this._groundTexture = null;
  89455. }
  89456. }
  89457. if (this._skybox && !newOptions.createSkybox) {
  89458. this._skybox.dispose();
  89459. this._skybox = null;
  89460. }
  89461. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89462. this._skyboxMaterial.dispose();
  89463. this._skyboxMaterial = null;
  89464. }
  89465. if (this._skyboxTexture) {
  89466. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89467. this._skyboxTexture.dispose();
  89468. this._skyboxTexture = null;
  89469. }
  89470. }
  89471. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89472. this._groundMirror.dispose();
  89473. this._groundMirror = null;
  89474. }
  89475. if (this._scene.environmentTexture) {
  89476. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89477. this._scene.environmentTexture.dispose();
  89478. }
  89479. }
  89480. this._options = newOptions;
  89481. this._setupBackground();
  89482. this._setupImageProcessing();
  89483. };
  89484. /**
  89485. * Sets the primary color of all the available elements.
  89486. * @param color
  89487. */
  89488. EnvironmentHelper.prototype.setMainColor = function (color) {
  89489. if (this.groundMaterial) {
  89490. this.groundMaterial.primaryColor = color;
  89491. }
  89492. if (this.skyboxMaterial) {
  89493. this.skyboxMaterial.primaryColor = color;
  89494. }
  89495. if (this.groundMirror) {
  89496. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89497. }
  89498. };
  89499. /**
  89500. * Setup the image processing according to the specified options.
  89501. */
  89502. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89503. if (this._options.setupImageProcessing) {
  89504. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89505. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89506. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89507. this._setupEnvironmentTexture();
  89508. }
  89509. };
  89510. /**
  89511. * Setup the environment texture according to the specified options.
  89512. */
  89513. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89514. if (this._scene.environmentTexture) {
  89515. return;
  89516. }
  89517. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89518. this._scene.environmentTexture = this._options.environmentTexture;
  89519. return;
  89520. }
  89521. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89522. this._scene.environmentTexture = environmentTexture;
  89523. };
  89524. /**
  89525. * Setup the background according to the specified options.
  89526. */
  89527. EnvironmentHelper.prototype._setupBackground = function () {
  89528. if (!this._rootMesh) {
  89529. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89530. }
  89531. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89532. var sceneSize = this._getSceneSize();
  89533. if (this._options.createGround) {
  89534. this._setupGround(sceneSize);
  89535. this._setupGroundMaterial();
  89536. this._setupGroundDiffuseTexture();
  89537. if (this._options.enableGroundMirror) {
  89538. this._setupGroundMirrorTexture(sceneSize);
  89539. }
  89540. this._setupMirrorInGroundMaterial();
  89541. }
  89542. if (this._options.createSkybox) {
  89543. this._setupSkybox(sceneSize);
  89544. this._setupSkyboxMaterial();
  89545. this._setupSkyboxReflectionTexture();
  89546. }
  89547. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89548. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89549. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89550. };
  89551. /**
  89552. * Get the scene sizes according to the setup.
  89553. */
  89554. EnvironmentHelper.prototype._getSceneSize = function () {
  89555. var _this = this;
  89556. var groundSize = this._options.groundSize;
  89557. var skyboxSize = this._options.skyboxSize;
  89558. var rootPosition = this._options.rootPosition;
  89559. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89560. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89561. }
  89562. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89563. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89564. });
  89565. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89566. if (this._options.sizeAuto) {
  89567. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89568. this._scene.activeCamera.upperRadiusLimit) {
  89569. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89570. skyboxSize = groundSize;
  89571. }
  89572. var sceneDiagonalLenght = sceneDiagonal.length();
  89573. if (sceneDiagonalLenght > groundSize) {
  89574. groundSize = sceneDiagonalLenght * 2;
  89575. skyboxSize = groundSize;
  89576. }
  89577. // 10 % bigger.
  89578. groundSize *= 1.1;
  89579. skyboxSize *= 1.5;
  89580. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89581. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89582. }
  89583. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89584. };
  89585. /**
  89586. * Setup the ground according to the specified options.
  89587. */
  89588. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89589. var _this = this;
  89590. if (!this._ground) {
  89591. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89592. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89593. this._ground.parent = this._rootMesh;
  89594. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89595. }
  89596. this._ground.receiveShadows = this._options.enableGroundShadow;
  89597. };
  89598. /**
  89599. * Setup the ground material according to the specified options.
  89600. */
  89601. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89602. if (!this._groundMaterial) {
  89603. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89604. }
  89605. this._groundMaterial.alpha = this._options.groundOpacity;
  89606. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89607. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89608. this._groundMaterial.primaryLevel = 1;
  89609. this._groundMaterial.primaryColor = this._options.groundColor;
  89610. this._groundMaterial.secondaryLevel = 0;
  89611. this._groundMaterial.tertiaryLevel = 0;
  89612. this._groundMaterial.useRGBColor = false;
  89613. this._groundMaterial.enableNoise = true;
  89614. if (this._ground) {
  89615. this._ground.material = this._groundMaterial;
  89616. }
  89617. };
  89618. /**
  89619. * Setup the ground diffuse texture according to the specified options.
  89620. */
  89621. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89622. if (!this._groundMaterial) {
  89623. return;
  89624. }
  89625. if (this._groundTexture) {
  89626. return;
  89627. }
  89628. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89629. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89630. return;
  89631. }
  89632. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89633. diffuseTexture.gammaSpace = false;
  89634. diffuseTexture.hasAlpha = true;
  89635. this._groundMaterial.diffuseTexture = diffuseTexture;
  89636. };
  89637. /**
  89638. * Setup the ground mirror texture according to the specified options.
  89639. */
  89640. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89641. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89642. if (!this._groundMirror) {
  89643. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89644. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89645. this._groundMirror.anisotropicFilteringLevel = 1;
  89646. this._groundMirror.wrapU = wrapping;
  89647. this._groundMirror.wrapV = wrapping;
  89648. this._groundMirror.gammaSpace = false;
  89649. if (this._groundMirror.renderList) {
  89650. for (var i = 0; i < this._scene.meshes.length; i++) {
  89651. var mesh = this._scene.meshes[i];
  89652. if (mesh !== this._ground &&
  89653. mesh !== this._skybox &&
  89654. mesh !== this._rootMesh) {
  89655. this._groundMirror.renderList.push(mesh);
  89656. }
  89657. }
  89658. }
  89659. }
  89660. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89661. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89662. };
  89663. /**
  89664. * Setup the ground to receive the mirror texture.
  89665. */
  89666. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89667. if (this._groundMaterial) {
  89668. this._groundMaterial.reflectionTexture = this._groundMirror;
  89669. this._groundMaterial.reflectionFresnel = true;
  89670. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89671. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89672. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89673. }
  89674. };
  89675. /**
  89676. * Setup the skybox according to the specified options.
  89677. */
  89678. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89679. var _this = this;
  89680. if (!this._skybox) {
  89681. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89682. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89683. }
  89684. this._skybox.parent = this._rootMesh;
  89685. };
  89686. /**
  89687. * Setup the skybox material according to the specified options.
  89688. */
  89689. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89690. if (!this._skybox) {
  89691. return;
  89692. }
  89693. if (!this._skyboxMaterial) {
  89694. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89695. }
  89696. this._skyboxMaterial.useRGBColor = false;
  89697. this._skyboxMaterial.primaryLevel = 1;
  89698. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89699. this._skyboxMaterial.secondaryLevel = 0;
  89700. this._skyboxMaterial.tertiaryLevel = 0;
  89701. this._skyboxMaterial.enableNoise = true;
  89702. this._skybox.material = this._skyboxMaterial;
  89703. };
  89704. /**
  89705. * Setup the skybox reflection texture according to the specified options.
  89706. */
  89707. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89708. if (!this._skyboxMaterial) {
  89709. return;
  89710. }
  89711. if (this._skyboxTexture) {
  89712. return;
  89713. }
  89714. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89715. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89716. return;
  89717. }
  89718. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89719. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89720. this._skyboxTexture.gammaSpace = false;
  89721. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89722. };
  89723. /**
  89724. * Dispose all the elements created by the Helper.
  89725. */
  89726. EnvironmentHelper.prototype.dispose = function () {
  89727. if (this._groundMaterial) {
  89728. this._groundMaterial.dispose(true, true);
  89729. }
  89730. if (this._skyboxMaterial) {
  89731. this._skyboxMaterial.dispose(true, true);
  89732. }
  89733. this._rootMesh.dispose(false);
  89734. };
  89735. /**
  89736. * Default ground texture URL.
  89737. */
  89738. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89739. /**
  89740. * Default skybox texture URL.
  89741. */
  89742. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89743. /**
  89744. * Default environment texture URL.
  89745. */
  89746. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89747. return EnvironmentHelper;
  89748. }());
  89749. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89750. })(BABYLON || (BABYLON = {}));
  89751. //# sourceMappingURL=babylon.environmentHelper.js.map
  89752. 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}","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","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","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}","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}","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}","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}","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"};
  89753. 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}","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","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};","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};"};
  89754. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89755. var BABYLON;
  89756. (function (BABYLON) {
  89757. var GridMaterialDefines = /** @class */ (function (_super) {
  89758. __extends(GridMaterialDefines, _super);
  89759. function GridMaterialDefines() {
  89760. var _this = _super.call(this) || this;
  89761. _this.TRANSPARENT = false;
  89762. _this.FOG = false;
  89763. _this.PREMULTIPLYALPHA = false;
  89764. _this.rebuild();
  89765. return _this;
  89766. }
  89767. return GridMaterialDefines;
  89768. }(BABYLON.MaterialDefines));
  89769. /**
  89770. * The grid materials allows you to wrap any shape with a grid.
  89771. * Colors are customizable.
  89772. */
  89773. var GridMaterial = /** @class */ (function (_super) {
  89774. __extends(GridMaterial, _super);
  89775. /**
  89776. * constructor
  89777. * @param name The name given to the material in order to identify it afterwards.
  89778. * @param scene The scene the material is used in.
  89779. */
  89780. function GridMaterial(name, scene) {
  89781. var _this = _super.call(this, name, scene) || this;
  89782. /**
  89783. * Main color of the grid (e.g. between lines)
  89784. */
  89785. _this.mainColor = BABYLON.Color3.Black();
  89786. /**
  89787. * Color of the grid lines.
  89788. */
  89789. _this.lineColor = BABYLON.Color3.Teal();
  89790. /**
  89791. * The scale of the grid compared to unit.
  89792. */
  89793. _this.gridRatio = 1.0;
  89794. /**
  89795. * Allows setting an offset for the grid lines.
  89796. */
  89797. _this.gridOffset = BABYLON.Vector3.Zero();
  89798. /**
  89799. * The frequency of thicker lines.
  89800. */
  89801. _this.majorUnitFrequency = 10;
  89802. /**
  89803. * The visibility of minor units in the grid.
  89804. */
  89805. _this.minorUnitVisibility = 0.33;
  89806. /**
  89807. * The grid opacity outside of the lines.
  89808. */
  89809. _this.opacity = 1.0;
  89810. /**
  89811. * Determine RBG output is premultiplied by alpha value.
  89812. */
  89813. _this.preMultiplyAlpha = false;
  89814. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  89815. return _this;
  89816. }
  89817. /**
  89818. * Returns wehter or not the grid requires alpha blending.
  89819. */
  89820. GridMaterial.prototype.needAlphaBlending = function () {
  89821. return this.opacity < 1.0;
  89822. };
  89823. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  89824. return this.needAlphaBlending();
  89825. };
  89826. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89827. if (this.isFrozen) {
  89828. if (this._wasPreviouslyReady && subMesh.effect) {
  89829. return true;
  89830. }
  89831. }
  89832. if (!subMesh._materialDefines) {
  89833. subMesh._materialDefines = new GridMaterialDefines();
  89834. }
  89835. var defines = subMesh._materialDefines;
  89836. var scene = this.getScene();
  89837. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89838. if (this._renderId === scene.getRenderId()) {
  89839. return true;
  89840. }
  89841. }
  89842. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  89843. defines.TRANSPARENT = !defines.TRANSPARENT;
  89844. defines.markAsUnprocessed();
  89845. }
  89846. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  89847. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  89848. defines.markAsUnprocessed();
  89849. }
  89850. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  89851. // Get correct effect
  89852. if (defines.isDirty) {
  89853. defines.markAsProcessed();
  89854. scene.resetCachedMaterial();
  89855. // Attributes
  89856. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89857. // Defines
  89858. var join = defines.toString();
  89859. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  89860. }
  89861. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89862. return false;
  89863. }
  89864. this._renderId = scene.getRenderId();
  89865. this._wasPreviouslyReady = true;
  89866. return true;
  89867. };
  89868. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89869. var scene = this.getScene();
  89870. var defines = subMesh._materialDefines;
  89871. if (!defines) {
  89872. return;
  89873. }
  89874. var effect = subMesh.effect;
  89875. if (!effect) {
  89876. return;
  89877. }
  89878. this._activeEffect = effect;
  89879. // Matrices
  89880. this.bindOnlyWorldMatrix(world);
  89881. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  89882. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  89883. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  89884. // Uniforms
  89885. if (this._mustRebind(scene, effect)) {
  89886. this._activeEffect.setColor3("mainColor", this.mainColor);
  89887. this._activeEffect.setColor3("lineColor", this.lineColor);
  89888. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  89889. this._gridControl.x = this.gridRatio;
  89890. this._gridControl.y = Math.round(this.majorUnitFrequency);
  89891. this._gridControl.z = this.minorUnitVisibility;
  89892. this._gridControl.w = this.opacity;
  89893. this._activeEffect.setVector4("gridControl", this._gridControl);
  89894. }
  89895. // Fog
  89896. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89897. this._afterBind(mesh, this._activeEffect);
  89898. };
  89899. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  89900. _super.prototype.dispose.call(this, forceDisposeEffect);
  89901. };
  89902. GridMaterial.prototype.clone = function (name) {
  89903. var _this = this;
  89904. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  89905. };
  89906. GridMaterial.prototype.serialize = function () {
  89907. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89908. serializationObject.customType = "BABYLON.GridMaterial";
  89909. return serializationObject;
  89910. };
  89911. GridMaterial.prototype.getClassName = function () {
  89912. return "GridMaterial";
  89913. };
  89914. GridMaterial.Parse = function (source, scene, rootUrl) {
  89915. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  89916. };
  89917. __decorate([
  89918. BABYLON.serializeAsColor3()
  89919. ], GridMaterial.prototype, "mainColor", void 0);
  89920. __decorate([
  89921. BABYLON.serializeAsColor3()
  89922. ], GridMaterial.prototype, "lineColor", void 0);
  89923. __decorate([
  89924. BABYLON.serialize()
  89925. ], GridMaterial.prototype, "gridRatio", void 0);
  89926. __decorate([
  89927. BABYLON.serializeAsColor3()
  89928. ], GridMaterial.prototype, "gridOffset", void 0);
  89929. __decorate([
  89930. BABYLON.serialize()
  89931. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  89932. __decorate([
  89933. BABYLON.serialize()
  89934. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  89935. __decorate([
  89936. BABYLON.serialize()
  89937. ], GridMaterial.prototype, "opacity", void 0);
  89938. __decorate([
  89939. BABYLON.serialize()
  89940. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  89941. return GridMaterial;
  89942. }(BABYLON.PushMaterial));
  89943. BABYLON.GridMaterial = GridMaterial;
  89944. })(BABYLON || (BABYLON = {}));
  89945. //# sourceMappingURL=babylon.gridmaterial.js.map
  89946. 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}";
  89947. 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}";
  89948. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89949. var BABYLON;
  89950. (function (BABYLON) {
  89951. var GLTFLoaderCoordinateSystemMode;
  89952. (function (GLTFLoaderCoordinateSystemMode) {
  89953. /**
  89954. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  89955. */
  89956. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  89957. /**
  89958. * Sets the useRightHandedSystem flag on the scene.
  89959. */
  89960. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  89961. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  89962. var GLTFLoaderAnimationStartMode;
  89963. (function (GLTFLoaderAnimationStartMode) {
  89964. /**
  89965. * No animation will start.
  89966. */
  89967. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  89968. /**
  89969. * The first animation will start.
  89970. */
  89971. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  89972. /**
  89973. * All animations will start.
  89974. */
  89975. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  89976. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  89977. var GLTFLoaderState;
  89978. (function (GLTFLoaderState) {
  89979. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  89980. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  89981. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  89982. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  89983. var GLTFFileLoader = /** @class */ (function () {
  89984. function GLTFFileLoader() {
  89985. // #region Common options
  89986. /**
  89987. * Raised when the asset has been parsed.
  89988. * The data.json property stores the glTF JSON.
  89989. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  89990. */
  89991. this.onParsedObservable = new BABYLON.Observable();
  89992. // #endregion
  89993. // #region V2 options
  89994. /**
  89995. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  89996. */
  89997. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  89998. /**
  89999. * The animation start mode (NONE, FIRST, ALL).
  90000. */
  90001. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  90002. /**
  90003. * Set to true to compile materials before raising the success callback.
  90004. */
  90005. this.compileMaterials = false;
  90006. /**
  90007. * Set to true to also compile materials with clip planes.
  90008. */
  90009. this.useClipPlane = false;
  90010. /**
  90011. * Set to true to compile shadow generators before raising the success callback.
  90012. */
  90013. this.compileShadowGenerators = false;
  90014. /**
  90015. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  90016. */
  90017. this.onMeshLoadedObservable = new BABYLON.Observable();
  90018. /**
  90019. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  90020. */
  90021. this.onTextureLoadedObservable = new BABYLON.Observable();
  90022. /**
  90023. * Raised when the loader creates a material after parsing the glTF properties of the material.
  90024. */
  90025. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90026. /**
  90027. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  90028. */
  90029. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  90030. /**
  90031. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  90032. * For assets with LODs, raised when all of the LODs are complete.
  90033. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  90034. */
  90035. this.onCompleteObservable = new BABYLON.Observable();
  90036. /**
  90037. * Raised when the loader is disposed.
  90038. */
  90039. this.onDisposeObservable = new BABYLON.Observable();
  90040. /**
  90041. * Raised after a loader extension is created.
  90042. * Set additional options for a loader extension in this event.
  90043. */
  90044. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90045. // #endregion
  90046. this._loader = null;
  90047. this.name = "gltf";
  90048. this.extensions = {
  90049. ".gltf": { isBinary: false },
  90050. ".glb": { isBinary: true }
  90051. };
  90052. }
  90053. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  90054. set: function (callback) {
  90055. if (this._onParsedObserver) {
  90056. this.onParsedObservable.remove(this._onParsedObserver);
  90057. }
  90058. this._onParsedObserver = this.onParsedObservable.add(callback);
  90059. },
  90060. enumerable: true,
  90061. configurable: true
  90062. });
  90063. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  90064. set: function (callback) {
  90065. if (this._onMeshLoadedObserver) {
  90066. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  90067. }
  90068. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  90069. },
  90070. enumerable: true,
  90071. configurable: true
  90072. });
  90073. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  90074. set: function (callback) {
  90075. if (this._onTextureLoadedObserver) {
  90076. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  90077. }
  90078. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  90079. },
  90080. enumerable: true,
  90081. configurable: true
  90082. });
  90083. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  90084. set: function (callback) {
  90085. if (this._onMaterialLoadedObserver) {
  90086. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  90087. }
  90088. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  90089. },
  90090. enumerable: true,
  90091. configurable: true
  90092. });
  90093. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  90094. set: function (callback) {
  90095. if (this._onAnimationGroupLoadedObserver) {
  90096. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  90097. }
  90098. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  90099. },
  90100. enumerable: true,
  90101. configurable: true
  90102. });
  90103. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  90104. set: function (callback) {
  90105. if (this._onCompleteObserver) {
  90106. this.onCompleteObservable.remove(this._onCompleteObserver);
  90107. }
  90108. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  90109. },
  90110. enumerable: true,
  90111. configurable: true
  90112. });
  90113. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  90114. set: function (callback) {
  90115. if (this._onDisposeObserver) {
  90116. this.onDisposeObservable.remove(this._onDisposeObserver);
  90117. }
  90118. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  90119. },
  90120. enumerable: true,
  90121. configurable: true
  90122. });
  90123. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  90124. set: function (callback) {
  90125. if (this._onExtensionLoadedObserver) {
  90126. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  90127. }
  90128. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  90129. },
  90130. enumerable: true,
  90131. configurable: true
  90132. });
  90133. /**
  90134. * Gets a promise that resolves when the asset is completely loaded.
  90135. * @returns A promise that resolves when the asset is completely loaded.
  90136. */
  90137. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  90138. var _this = this;
  90139. return new Promise(function (resolve) {
  90140. _this.onCompleteObservable.add(function () {
  90141. resolve();
  90142. }, undefined, undefined, undefined, true);
  90143. });
  90144. };
  90145. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  90146. /**
  90147. * The loader state or null if not active.
  90148. */
  90149. get: function () {
  90150. return this._loader ? this._loader.state : null;
  90151. },
  90152. enumerable: true,
  90153. configurable: true
  90154. });
  90155. /**
  90156. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  90157. */
  90158. GLTFFileLoader.prototype.dispose = function () {
  90159. if (this._loader) {
  90160. this._loader.dispose();
  90161. this._loader = null;
  90162. }
  90163. this.onMeshLoadedObservable.clear();
  90164. this.onTextureLoadedObservable.clear();
  90165. this.onMaterialLoadedObservable.clear();
  90166. this.onDisposeObservable.notifyObservers(this);
  90167. this.onDisposeObservable.clear();
  90168. };
  90169. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90170. var _this = this;
  90171. return Promise.resolve().then(function () {
  90172. var loaderData = _this._parse(data);
  90173. _this._loader = _this._getLoader(loaderData);
  90174. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  90175. });
  90176. };
  90177. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90178. var _this = this;
  90179. return Promise.resolve().then(function () {
  90180. var loaderData = _this._parse(data);
  90181. _this._loader = _this._getLoader(loaderData);
  90182. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  90183. });
  90184. };
  90185. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  90186. var _this = this;
  90187. return Promise.resolve().then(function () {
  90188. var loaderData = _this._parse(data);
  90189. _this._loader = _this._getLoader(loaderData);
  90190. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  90191. var container = new BABYLON.AssetContainer(scene);
  90192. Array.prototype.push.apply(container.meshes, result.meshes);
  90193. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  90194. Array.prototype.push.apply(container.skeletons, result.skeletons);
  90195. container.removeAllFromScene();
  90196. return container;
  90197. });
  90198. });
  90199. };
  90200. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  90201. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  90202. };
  90203. GLTFFileLoader.prototype.createPlugin = function () {
  90204. return new GLTFFileLoader();
  90205. };
  90206. GLTFFileLoader.prototype._parse = function (data) {
  90207. var parsedData;
  90208. if (data instanceof ArrayBuffer) {
  90209. parsedData = GLTFFileLoader._parseBinary(data);
  90210. }
  90211. else {
  90212. parsedData = {
  90213. json: JSON.parse(data),
  90214. bin: null
  90215. };
  90216. }
  90217. this.onParsedObservable.notifyObservers(parsedData);
  90218. this.onParsedObservable.clear();
  90219. return parsedData;
  90220. };
  90221. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  90222. var _this = this;
  90223. var loaderVersion = { major: 2, minor: 0 };
  90224. var asset = loaderData.json.asset || {};
  90225. var version = GLTFFileLoader._parseVersion(asset.version);
  90226. if (!version) {
  90227. throw new Error("Invalid version: " + asset.version);
  90228. }
  90229. if (asset.minVersion !== undefined) {
  90230. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  90231. if (!minVersion) {
  90232. throw new Error("Invalid minimum version: " + asset.minVersion);
  90233. }
  90234. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  90235. throw new Error("Incompatible minimum version: " + asset.minVersion);
  90236. }
  90237. }
  90238. var createLoaders = {
  90239. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  90240. 2: GLTFFileLoader.CreateGLTFLoaderV2
  90241. };
  90242. var createLoader = createLoaders[version.major];
  90243. if (!createLoader) {
  90244. throw new Error("Unsupported version: " + asset.version);
  90245. }
  90246. var loader = createLoader();
  90247. loader.coordinateSystemMode = this.coordinateSystemMode;
  90248. loader.animationStartMode = this.animationStartMode;
  90249. loader.compileMaterials = this.compileMaterials;
  90250. loader.useClipPlane = this.useClipPlane;
  90251. loader.compileShadowGenerators = this.compileShadowGenerators;
  90252. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  90253. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  90254. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  90255. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  90256. loader.onCompleteObservable.add(function () {
  90257. _this.onMeshLoadedObservable.clear();
  90258. _this.onTextureLoadedObservable.clear();
  90259. _this.onMaterialLoadedObservable.clear();
  90260. _this.onCompleteObservable.notifyObservers(_this);
  90261. _this.onCompleteObservable.clear();
  90262. });
  90263. return loader;
  90264. };
  90265. GLTFFileLoader._parseBinary = function (data) {
  90266. var Binary = {
  90267. Magic: 0x46546C67
  90268. };
  90269. var binaryReader = new BinaryReader(data);
  90270. var magic = binaryReader.readUint32();
  90271. if (magic !== Binary.Magic) {
  90272. throw new Error("Unexpected magic: " + magic);
  90273. }
  90274. var version = binaryReader.readUint32();
  90275. switch (version) {
  90276. case 1: return GLTFFileLoader._parseV1(binaryReader);
  90277. case 2: return GLTFFileLoader._parseV2(binaryReader);
  90278. }
  90279. throw new Error("Unsupported version: " + version);
  90280. };
  90281. GLTFFileLoader._parseV1 = function (binaryReader) {
  90282. var ContentFormat = {
  90283. JSON: 0
  90284. };
  90285. var length = binaryReader.readUint32();
  90286. if (length != binaryReader.getLength()) {
  90287. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90288. }
  90289. var contentLength = binaryReader.readUint32();
  90290. var contentFormat = binaryReader.readUint32();
  90291. var content;
  90292. switch (contentFormat) {
  90293. case ContentFormat.JSON: {
  90294. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  90295. break;
  90296. }
  90297. default: {
  90298. throw new Error("Unexpected content format: " + contentFormat);
  90299. }
  90300. }
  90301. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  90302. var body = binaryReader.readUint8Array(bytesRemaining);
  90303. return {
  90304. json: content,
  90305. bin: body
  90306. };
  90307. };
  90308. GLTFFileLoader._parseV2 = function (binaryReader) {
  90309. var ChunkFormat = {
  90310. JSON: 0x4E4F534A,
  90311. BIN: 0x004E4942
  90312. };
  90313. var length = binaryReader.readUint32();
  90314. if (length !== binaryReader.getLength()) {
  90315. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90316. }
  90317. // JSON chunk
  90318. var chunkLength = binaryReader.readUint32();
  90319. var chunkFormat = binaryReader.readUint32();
  90320. if (chunkFormat !== ChunkFormat.JSON) {
  90321. throw new Error("First chunk format is not JSON");
  90322. }
  90323. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  90324. // Look for BIN chunk
  90325. var bin = null;
  90326. while (binaryReader.getPosition() < binaryReader.getLength()) {
  90327. var chunkLength_1 = binaryReader.readUint32();
  90328. var chunkFormat_1 = binaryReader.readUint32();
  90329. switch (chunkFormat_1) {
  90330. case ChunkFormat.JSON: {
  90331. throw new Error("Unexpected JSON chunk");
  90332. }
  90333. case ChunkFormat.BIN: {
  90334. bin = binaryReader.readUint8Array(chunkLength_1);
  90335. break;
  90336. }
  90337. default: {
  90338. // ignore unrecognized chunkFormat
  90339. binaryReader.skipBytes(chunkLength_1);
  90340. break;
  90341. }
  90342. }
  90343. }
  90344. return {
  90345. json: json,
  90346. bin: bin
  90347. };
  90348. };
  90349. GLTFFileLoader._parseVersion = function (version) {
  90350. if (version === "1.0" || version === "1.0.1") {
  90351. return {
  90352. major: 1,
  90353. minor: 0
  90354. };
  90355. }
  90356. var match = (version + "").match(/^(\d+)\.(\d+)/);
  90357. if (!match) {
  90358. return null;
  90359. }
  90360. return {
  90361. major: parseInt(match[1]),
  90362. minor: parseInt(match[2])
  90363. };
  90364. };
  90365. GLTFFileLoader._compareVersion = function (a, b) {
  90366. if (a.major > b.major)
  90367. return 1;
  90368. if (a.major < b.major)
  90369. return -1;
  90370. if (a.minor > b.minor)
  90371. return 1;
  90372. if (a.minor < b.minor)
  90373. return -1;
  90374. return 0;
  90375. };
  90376. GLTFFileLoader._decodeBufferToText = function (buffer) {
  90377. var result = "";
  90378. var length = buffer.byteLength;
  90379. for (var i = 0; i < length; i++) {
  90380. result += String.fromCharCode(buffer[i]);
  90381. }
  90382. return result;
  90383. };
  90384. // #endregion
  90385. // #region V1 options
  90386. GLTFFileLoader.IncrementalLoading = true;
  90387. GLTFFileLoader.HomogeneousCoordinates = false;
  90388. return GLTFFileLoader;
  90389. }());
  90390. BABYLON.GLTFFileLoader = GLTFFileLoader;
  90391. var BinaryReader = /** @class */ (function () {
  90392. function BinaryReader(arrayBuffer) {
  90393. this._arrayBuffer = arrayBuffer;
  90394. this._dataView = new DataView(arrayBuffer);
  90395. this._byteOffset = 0;
  90396. }
  90397. BinaryReader.prototype.getPosition = function () {
  90398. return this._byteOffset;
  90399. };
  90400. BinaryReader.prototype.getLength = function () {
  90401. return this._arrayBuffer.byteLength;
  90402. };
  90403. BinaryReader.prototype.readUint32 = function () {
  90404. var value = this._dataView.getUint32(this._byteOffset, true);
  90405. this._byteOffset += 4;
  90406. return value;
  90407. };
  90408. BinaryReader.prototype.readUint8Array = function (length) {
  90409. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  90410. this._byteOffset += length;
  90411. return value;
  90412. };
  90413. BinaryReader.prototype.skipBytes = function (length) {
  90414. this._byteOffset += length;
  90415. };
  90416. return BinaryReader;
  90417. }());
  90418. if (BABYLON.SceneLoader) {
  90419. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  90420. }
  90421. })(BABYLON || (BABYLON = {}));
  90422. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  90423. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90424. var BABYLON;
  90425. (function (BABYLON) {
  90426. var GLTF1;
  90427. (function (GLTF1) {
  90428. /**
  90429. * Enums
  90430. */
  90431. var EComponentType;
  90432. (function (EComponentType) {
  90433. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  90434. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90435. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  90436. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90437. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  90438. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  90439. var EShaderType;
  90440. (function (EShaderType) {
  90441. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  90442. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  90443. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  90444. var EParameterType;
  90445. (function (EParameterType) {
  90446. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90447. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90448. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90449. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90450. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90451. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90452. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90453. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90454. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90455. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90456. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90457. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90458. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90459. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90460. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90461. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90462. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90463. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90464. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90465. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90466. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90467. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90468. var ETextureWrapMode;
  90469. (function (ETextureWrapMode) {
  90470. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90471. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90472. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90473. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90474. var ETextureFilterType;
  90475. (function (ETextureFilterType) {
  90476. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90477. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90478. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90479. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90480. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90481. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90482. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90483. var ETextureFormat;
  90484. (function (ETextureFormat) {
  90485. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90486. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90487. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90488. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90489. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90490. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90491. var ECullingType;
  90492. (function (ECullingType) {
  90493. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90494. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90495. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90496. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90497. var EBlendingFunction;
  90498. (function (EBlendingFunction) {
  90499. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90500. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90501. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90502. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90503. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90504. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90505. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90506. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90507. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90508. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90509. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90510. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90511. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90512. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90513. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90514. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90515. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90516. })(BABYLON || (BABYLON = {}));
  90517. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90518. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90519. var BABYLON;
  90520. (function (BABYLON) {
  90521. var GLTF1;
  90522. (function (GLTF1) {
  90523. /**
  90524. * Tokenizer. Used for shaders compatibility
  90525. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90526. */
  90527. var ETokenType;
  90528. (function (ETokenType) {
  90529. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90530. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90531. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90532. })(ETokenType || (ETokenType = {}));
  90533. var Tokenizer = /** @class */ (function () {
  90534. function Tokenizer(toParse) {
  90535. this._pos = 0;
  90536. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90537. this._toParse = toParse;
  90538. this._maxPos = toParse.length;
  90539. }
  90540. Tokenizer.prototype.getNextToken = function () {
  90541. if (this.isEnd())
  90542. return ETokenType.END_OF_INPUT;
  90543. this.currentString = this.read();
  90544. this.currentToken = ETokenType.UNKNOWN;
  90545. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90546. this.currentToken = ETokenType.IDENTIFIER;
  90547. this.currentIdentifier = this.currentString;
  90548. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90549. this.currentIdentifier += this.currentString;
  90550. this.forward();
  90551. }
  90552. }
  90553. return this.currentToken;
  90554. };
  90555. Tokenizer.prototype.peek = function () {
  90556. return this._toParse[this._pos];
  90557. };
  90558. Tokenizer.prototype.read = function () {
  90559. return this._toParse[this._pos++];
  90560. };
  90561. Tokenizer.prototype.forward = function () {
  90562. this._pos++;
  90563. };
  90564. Tokenizer.prototype.isEnd = function () {
  90565. return this._pos >= this._maxPos;
  90566. };
  90567. return Tokenizer;
  90568. }());
  90569. /**
  90570. * Values
  90571. */
  90572. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90573. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90574. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90575. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90576. /**
  90577. * Parse
  90578. */
  90579. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90580. for (var buf in parsedBuffers) {
  90581. var parsedBuffer = parsedBuffers[buf];
  90582. gltfRuntime.buffers[buf] = parsedBuffer;
  90583. gltfRuntime.buffersCount++;
  90584. }
  90585. };
  90586. var parseShaders = function (parsedShaders, gltfRuntime) {
  90587. for (var sha in parsedShaders) {
  90588. var parsedShader = parsedShaders[sha];
  90589. gltfRuntime.shaders[sha] = parsedShader;
  90590. gltfRuntime.shaderscount++;
  90591. }
  90592. };
  90593. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90594. for (var object in parsedObjects) {
  90595. var parsedObject = parsedObjects[object];
  90596. gltfRuntime[runtimeProperty][object] = parsedObject;
  90597. }
  90598. };
  90599. /**
  90600. * Utils
  90601. */
  90602. var normalizeUVs = function (buffer) {
  90603. if (!buffer) {
  90604. return;
  90605. }
  90606. for (var i = 0; i < buffer.length / 2; i++) {
  90607. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90608. }
  90609. };
  90610. var getAttribute = function (attributeParameter) {
  90611. if (attributeParameter.semantic === "NORMAL") {
  90612. return "normal";
  90613. }
  90614. else if (attributeParameter.semantic === "POSITION") {
  90615. return "position";
  90616. }
  90617. else if (attributeParameter.semantic === "JOINT") {
  90618. return "matricesIndices";
  90619. }
  90620. else if (attributeParameter.semantic === "WEIGHT") {
  90621. return "matricesWeights";
  90622. }
  90623. else if (attributeParameter.semantic === "COLOR") {
  90624. return "color";
  90625. }
  90626. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90627. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90628. return "uv" + (channel === 0 ? "" : channel + 1);
  90629. }
  90630. return null;
  90631. };
  90632. /**
  90633. * Loads and creates animations
  90634. */
  90635. var loadAnimations = function (gltfRuntime) {
  90636. for (var anim in gltfRuntime.animations) {
  90637. var animation = gltfRuntime.animations[anim];
  90638. if (!animation.channels || !animation.samplers) {
  90639. continue;
  90640. }
  90641. var lastAnimation = null;
  90642. for (var i = 0; i < animation.channels.length; i++) {
  90643. // Get parameters and load buffers
  90644. var channel = animation.channels[i];
  90645. var sampler = animation.samplers[channel.sampler];
  90646. if (!sampler) {
  90647. continue;
  90648. }
  90649. var inputData = null;
  90650. var outputData = null;
  90651. if (animation.parameters) {
  90652. inputData = animation.parameters[sampler.input];
  90653. outputData = animation.parameters[sampler.output];
  90654. }
  90655. else {
  90656. inputData = sampler.input;
  90657. outputData = sampler.output;
  90658. }
  90659. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90660. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  90661. var targetID = channel.target.id;
  90662. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  90663. if (targetNode === null) {
  90664. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  90665. }
  90666. if (targetNode === null) {
  90667. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  90668. continue;
  90669. }
  90670. var isBone = targetNode instanceof BABYLON.Bone;
  90671. // Get target path (position, rotation or scaling)
  90672. var targetPath = channel.target.path;
  90673. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  90674. if (targetPathIndex !== -1) {
  90675. targetPath = babylonAnimationPaths[targetPathIndex];
  90676. }
  90677. // Determine animation type
  90678. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  90679. if (!isBone) {
  90680. if (targetPath === "rotationQuaternion") {
  90681. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90682. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  90683. }
  90684. else {
  90685. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90686. }
  90687. }
  90688. // Create animation and key frames
  90689. var babylonAnimation = null;
  90690. var keys = [];
  90691. var arrayOffset = 0;
  90692. var modifyKey = false;
  90693. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  90694. babylonAnimation = lastAnimation;
  90695. modifyKey = true;
  90696. }
  90697. if (!modifyKey) {
  90698. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90699. }
  90700. // For each frame
  90701. for (var j = 0; j < bufferInput.length; j++) {
  90702. var value = null;
  90703. if (targetPath === "rotationQuaternion") {
  90704. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  90705. arrayOffset += 4;
  90706. }
  90707. else {
  90708. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  90709. arrayOffset += 3;
  90710. }
  90711. if (isBone) {
  90712. var bone = targetNode;
  90713. var translation = BABYLON.Vector3.Zero();
  90714. var rotationQuaternion = new BABYLON.Quaternion();
  90715. var scaling = BABYLON.Vector3.Zero();
  90716. // Warning on decompose
  90717. var mat = bone.getBaseMatrix();
  90718. if (modifyKey && lastAnimation) {
  90719. mat = lastAnimation.getKeys()[j].value;
  90720. }
  90721. mat.decompose(scaling, rotationQuaternion, translation);
  90722. if (targetPath === "position") {
  90723. translation = value;
  90724. }
  90725. else if (targetPath === "rotationQuaternion") {
  90726. rotationQuaternion = value;
  90727. }
  90728. else {
  90729. scaling = value;
  90730. }
  90731. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  90732. }
  90733. if (!modifyKey) {
  90734. keys.push({
  90735. frame: bufferInput[j],
  90736. value: value
  90737. });
  90738. }
  90739. else if (lastAnimation) {
  90740. lastAnimation.getKeys()[j].value = value;
  90741. }
  90742. }
  90743. // Finish
  90744. if (!modifyKey && babylonAnimation) {
  90745. babylonAnimation.setKeys(keys);
  90746. targetNode.animations.push(babylonAnimation);
  90747. }
  90748. lastAnimation = babylonAnimation;
  90749. gltfRuntime.scene.stopAnimation(targetNode);
  90750. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  90751. }
  90752. }
  90753. };
  90754. /**
  90755. * Returns the bones transformation matrix
  90756. */
  90757. var configureBoneTransformation = function (node) {
  90758. var mat = null;
  90759. if (node.translation || node.rotation || node.scale) {
  90760. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  90761. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  90762. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  90763. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  90764. }
  90765. else {
  90766. mat = BABYLON.Matrix.FromArray(node.matrix);
  90767. }
  90768. return mat;
  90769. };
  90770. /**
  90771. * Returns the parent bone
  90772. */
  90773. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  90774. // Try to find
  90775. for (var i = 0; i < newSkeleton.bones.length; i++) {
  90776. if (newSkeleton.bones[i].name === jointName) {
  90777. return newSkeleton.bones[i];
  90778. }
  90779. }
  90780. // Not found, search in gltf nodes
  90781. var nodes = gltfRuntime.nodes;
  90782. for (var nde in nodes) {
  90783. var node = nodes[nde];
  90784. if (!node.jointName) {
  90785. continue;
  90786. }
  90787. var children = node.children;
  90788. for (var i = 0; i < children.length; i++) {
  90789. var child = gltfRuntime.nodes[children[i]];
  90790. if (!child.jointName) {
  90791. continue;
  90792. }
  90793. if (child.jointName === jointName) {
  90794. var mat = configureBoneTransformation(node);
  90795. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  90796. bone.id = nde;
  90797. return bone;
  90798. }
  90799. }
  90800. }
  90801. return null;
  90802. };
  90803. /**
  90804. * Returns the appropriate root node
  90805. */
  90806. var getNodeToRoot = function (nodesToRoot, id) {
  90807. for (var i = 0; i < nodesToRoot.length; i++) {
  90808. var nodeToRoot = nodesToRoot[i];
  90809. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  90810. var child = nodeToRoot.node.children[j];
  90811. if (child === id) {
  90812. return nodeToRoot.bone;
  90813. }
  90814. }
  90815. }
  90816. return null;
  90817. };
  90818. /**
  90819. * Returns the node with the joint name
  90820. */
  90821. var getJointNode = function (gltfRuntime, jointName) {
  90822. var nodes = gltfRuntime.nodes;
  90823. var node = nodes[jointName];
  90824. if (node) {
  90825. return {
  90826. node: node,
  90827. id: jointName
  90828. };
  90829. }
  90830. for (var nde in nodes) {
  90831. node = nodes[nde];
  90832. if (node.jointName === jointName) {
  90833. return {
  90834. node: node,
  90835. id: nde
  90836. };
  90837. }
  90838. }
  90839. return null;
  90840. };
  90841. /**
  90842. * Checks if a nodes is in joints
  90843. */
  90844. var nodeIsInJoints = function (skins, id) {
  90845. for (var i = 0; i < skins.jointNames.length; i++) {
  90846. if (skins.jointNames[i] === id) {
  90847. return true;
  90848. }
  90849. }
  90850. return false;
  90851. };
  90852. /**
  90853. * Fills the nodes to root for bones and builds hierarchy
  90854. */
  90855. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  90856. // Creates nodes for root
  90857. for (var nde in gltfRuntime.nodes) {
  90858. var node = gltfRuntime.nodes[nde];
  90859. var id = nde;
  90860. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  90861. continue;
  90862. }
  90863. // Create node to root bone
  90864. var mat = configureBoneTransformation(node);
  90865. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  90866. bone.id = id;
  90867. nodesToRoot.push({ bone: bone, node: node, id: id });
  90868. }
  90869. // Parenting
  90870. for (var i = 0; i < nodesToRoot.length; i++) {
  90871. var nodeToRoot = nodesToRoot[i];
  90872. var children = nodeToRoot.node.children;
  90873. for (var j = 0; j < children.length; j++) {
  90874. var child = null;
  90875. for (var k = 0; k < nodesToRoot.length; k++) {
  90876. if (nodesToRoot[k].id === children[j]) {
  90877. child = nodesToRoot[k];
  90878. break;
  90879. }
  90880. }
  90881. if (child) {
  90882. child.bone._parent = nodeToRoot.bone;
  90883. nodeToRoot.bone.children.push(child.bone);
  90884. }
  90885. }
  90886. }
  90887. };
  90888. /**
  90889. * Imports a skeleton
  90890. */
  90891. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  90892. if (!newSkeleton) {
  90893. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  90894. }
  90895. if (!skins.babylonSkeleton) {
  90896. return newSkeleton;
  90897. }
  90898. // Find the root bones
  90899. var nodesToRoot = [];
  90900. var nodesToRootToAdd = [];
  90901. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  90902. newSkeleton.bones = [];
  90903. // Joints
  90904. for (var i = 0; i < skins.jointNames.length; i++) {
  90905. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90906. if (!jointNode) {
  90907. continue;
  90908. }
  90909. var node = jointNode.node;
  90910. if (!node) {
  90911. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  90912. continue;
  90913. }
  90914. var id = jointNode.id;
  90915. // Optimize, if the bone already exists...
  90916. var existingBone = gltfRuntime.scene.getBoneByID(id);
  90917. if (existingBone) {
  90918. newSkeleton.bones.push(existingBone);
  90919. continue;
  90920. }
  90921. // Search for parent bone
  90922. var foundBone = false;
  90923. var parentBone = null;
  90924. for (var j = 0; j < i; j++) {
  90925. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  90926. if (!jointNode_1) {
  90927. continue;
  90928. }
  90929. var joint = jointNode_1.node;
  90930. if (!joint) {
  90931. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  90932. continue;
  90933. }
  90934. var children = joint.children;
  90935. if (!children) {
  90936. continue;
  90937. }
  90938. foundBone = false;
  90939. for (var k = 0; k < children.length; k++) {
  90940. if (children[k] === id) {
  90941. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  90942. foundBone = true;
  90943. break;
  90944. }
  90945. }
  90946. if (foundBone) {
  90947. break;
  90948. }
  90949. }
  90950. // Create bone
  90951. var mat = configureBoneTransformation(node);
  90952. if (!parentBone && nodesToRoot.length > 0) {
  90953. parentBone = getNodeToRoot(nodesToRoot, id);
  90954. if (parentBone) {
  90955. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  90956. nodesToRootToAdd.push(parentBone);
  90957. }
  90958. }
  90959. }
  90960. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  90961. bone.id = id;
  90962. }
  90963. // Polish
  90964. var bones = newSkeleton.bones;
  90965. newSkeleton.bones = [];
  90966. for (var i = 0; i < skins.jointNames.length; i++) {
  90967. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90968. if (!jointNode) {
  90969. continue;
  90970. }
  90971. for (var j = 0; j < bones.length; j++) {
  90972. if (bones[j].id === jointNode.id) {
  90973. newSkeleton.bones.push(bones[j]);
  90974. break;
  90975. }
  90976. }
  90977. }
  90978. newSkeleton.prepare();
  90979. // Finish
  90980. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  90981. newSkeleton.bones.push(nodesToRootToAdd[i]);
  90982. }
  90983. return newSkeleton;
  90984. };
  90985. /**
  90986. * Imports a mesh and its geometries
  90987. */
  90988. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  90989. if (!newMesh) {
  90990. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90991. newMesh.id = id;
  90992. }
  90993. if (!node.babylonNode) {
  90994. return newMesh;
  90995. }
  90996. var subMaterials = [];
  90997. var vertexData = null;
  90998. var verticesStarts = new Array();
  90999. var verticesCounts = new Array();
  91000. var indexStarts = new Array();
  91001. var indexCounts = new Array();
  91002. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91003. var meshID = meshes[meshIndex];
  91004. var mesh = gltfRuntime.meshes[meshID];
  91005. if (!mesh) {
  91006. continue;
  91007. }
  91008. // Positions, normals and UVs
  91009. for (var i = 0; i < mesh.primitives.length; i++) {
  91010. // Temporary vertex data
  91011. var tempVertexData = new BABYLON.VertexData();
  91012. var primitive = mesh.primitives[i];
  91013. if (primitive.mode !== 4) {
  91014. // continue;
  91015. }
  91016. var attributes = primitive.attributes;
  91017. var accessor = null;
  91018. var buffer = null;
  91019. // Set positions, normal and uvs
  91020. for (var semantic in attributes) {
  91021. // Link accessor and buffer view
  91022. accessor = gltfRuntime.accessors[attributes[semantic]];
  91023. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91024. if (semantic === "NORMAL") {
  91025. tempVertexData.normals = new Float32Array(buffer.length);
  91026. tempVertexData.normals.set(buffer);
  91027. }
  91028. else if (semantic === "POSITION") {
  91029. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  91030. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  91031. for (var j = 0; j < buffer.length; j += 4) {
  91032. tempVertexData.positions[j] = buffer[j];
  91033. tempVertexData.positions[j + 1] = buffer[j + 1];
  91034. tempVertexData.positions[j + 2] = buffer[j + 2];
  91035. }
  91036. }
  91037. else {
  91038. tempVertexData.positions = new Float32Array(buffer.length);
  91039. tempVertexData.positions.set(buffer);
  91040. }
  91041. verticesCounts.push(tempVertexData.positions.length);
  91042. }
  91043. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  91044. var channel = Number(semantic.split("_")[1]);
  91045. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  91046. var uvs = new Float32Array(buffer.length);
  91047. uvs.set(buffer);
  91048. normalizeUVs(uvs);
  91049. tempVertexData.set(uvs, uvKind);
  91050. }
  91051. else if (semantic === "JOINT") {
  91052. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  91053. tempVertexData.matricesIndices.set(buffer);
  91054. }
  91055. else if (semantic === "WEIGHT") {
  91056. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  91057. tempVertexData.matricesWeights.set(buffer);
  91058. }
  91059. else if (semantic === "COLOR") {
  91060. tempVertexData.colors = new Float32Array(buffer.length);
  91061. tempVertexData.colors.set(buffer);
  91062. }
  91063. }
  91064. // Indices
  91065. accessor = gltfRuntime.accessors[primitive.indices];
  91066. if (accessor) {
  91067. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91068. tempVertexData.indices = new Int32Array(buffer.length);
  91069. tempVertexData.indices.set(buffer);
  91070. indexCounts.push(tempVertexData.indices.length);
  91071. }
  91072. else {
  91073. // Set indices on the fly
  91074. var indices = [];
  91075. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  91076. indices.push(j);
  91077. }
  91078. tempVertexData.indices = new Int32Array(indices);
  91079. indexCounts.push(tempVertexData.indices.length);
  91080. }
  91081. if (!vertexData) {
  91082. vertexData = tempVertexData;
  91083. }
  91084. else {
  91085. vertexData.merge(tempVertexData);
  91086. }
  91087. // Sub material
  91088. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  91089. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  91090. // Update vertices start and index start
  91091. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  91092. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  91093. }
  91094. }
  91095. var material;
  91096. if (subMaterials.length > 1) {
  91097. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  91098. material.subMaterials = subMaterials;
  91099. }
  91100. else {
  91101. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  91102. }
  91103. if (subMaterials.length === 1) {
  91104. material = subMaterials[0];
  91105. }
  91106. if (!newMesh.material) {
  91107. newMesh.material = material;
  91108. }
  91109. // Apply geometry
  91110. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  91111. newMesh.computeWorldMatrix(true);
  91112. // Apply submeshes
  91113. newMesh.subMeshes = [];
  91114. var index = 0;
  91115. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91116. var meshID = meshes[meshIndex];
  91117. var mesh = gltfRuntime.meshes[meshID];
  91118. if (!mesh) {
  91119. continue;
  91120. }
  91121. for (var i = 0; i < mesh.primitives.length; i++) {
  91122. if (mesh.primitives[i].mode !== 4) {
  91123. //continue;
  91124. }
  91125. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  91126. index++;
  91127. }
  91128. }
  91129. // Finish
  91130. return newMesh;
  91131. };
  91132. /**
  91133. * Configure node transformation from position, rotation and scaling
  91134. */
  91135. var configureNode = function (newNode, position, rotation, scaling) {
  91136. if (newNode.position) {
  91137. newNode.position = position;
  91138. }
  91139. if (newNode.rotationQuaternion || newNode.rotation) {
  91140. newNode.rotationQuaternion = rotation;
  91141. }
  91142. if (newNode.scaling) {
  91143. newNode.scaling = scaling;
  91144. }
  91145. };
  91146. /**
  91147. * Configures node from transformation matrix
  91148. */
  91149. var configureNodeFromMatrix = function (newNode, node, parent) {
  91150. if (node.matrix) {
  91151. var position = new BABYLON.Vector3(0, 0, 0);
  91152. var rotation = new BABYLON.Quaternion();
  91153. var scaling = new BABYLON.Vector3(0, 0, 0);
  91154. var mat = BABYLON.Matrix.FromArray(node.matrix);
  91155. mat.decompose(scaling, rotation, position);
  91156. configureNode(newNode, position, rotation, scaling);
  91157. }
  91158. else if (node.translation && node.rotation && node.scale) {
  91159. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  91160. }
  91161. newNode.computeWorldMatrix(true);
  91162. };
  91163. /**
  91164. * Imports a node
  91165. */
  91166. var importNode = function (gltfRuntime, node, id, parent) {
  91167. var lastNode = null;
  91168. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  91169. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  91170. return null;
  91171. }
  91172. }
  91173. // Meshes
  91174. if (node.skin) {
  91175. if (node.meshes) {
  91176. var skin = gltfRuntime.skins[node.skin];
  91177. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  91178. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  91179. if (newMesh.skeleton === null) {
  91180. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  91181. if (!skin.babylonSkeleton) {
  91182. skin.babylonSkeleton = newMesh.skeleton;
  91183. }
  91184. }
  91185. lastNode = newMesh;
  91186. }
  91187. }
  91188. else if (node.meshes) {
  91189. /**
  91190. * Improve meshes property
  91191. */
  91192. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  91193. lastNode = newMesh;
  91194. }
  91195. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91196. var light = gltfRuntime.lights[node.light];
  91197. if (light) {
  91198. if (light.type === "ambient") {
  91199. var ambienLight = light[light.type];
  91200. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91201. hemiLight.name = node.name || "";
  91202. if (ambienLight.color) {
  91203. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  91204. }
  91205. lastNode = hemiLight;
  91206. }
  91207. else if (light.type === "directional") {
  91208. var directionalLight = light[light.type];
  91209. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91210. dirLight.name = node.name || "";
  91211. if (directionalLight.color) {
  91212. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  91213. }
  91214. lastNode = dirLight;
  91215. }
  91216. else if (light.type === "point") {
  91217. var pointLight = light[light.type];
  91218. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91219. ptLight.name = node.name || "";
  91220. if (pointLight.color) {
  91221. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  91222. }
  91223. lastNode = ptLight;
  91224. }
  91225. else if (light.type === "spot") {
  91226. var spotLight = light[light.type];
  91227. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  91228. spLight.name = node.name || "";
  91229. if (spotLight.color) {
  91230. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  91231. }
  91232. if (spotLight.fallOfAngle) {
  91233. spLight.angle = spotLight.fallOfAngle;
  91234. }
  91235. if (spotLight.fallOffExponent) {
  91236. spLight.exponent = spotLight.fallOffExponent;
  91237. }
  91238. lastNode = spLight;
  91239. }
  91240. }
  91241. }
  91242. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91243. var camera = gltfRuntime.cameras[node.camera];
  91244. if (camera) {
  91245. if (camera.type === "orthographic") {
  91246. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91247. orthoCamera.name = node.name || "";
  91248. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  91249. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91250. lastNode = orthoCamera;
  91251. }
  91252. else if (camera.type === "perspective") {
  91253. var perspectiveCamera = camera[camera.type];
  91254. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91255. persCamera.name = node.name || "";
  91256. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91257. if (!perspectiveCamera.aspectRatio) {
  91258. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  91259. }
  91260. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  91261. persCamera.maxZ = perspectiveCamera.zfar;
  91262. persCamera.minZ = perspectiveCamera.znear;
  91263. }
  91264. lastNode = persCamera;
  91265. }
  91266. }
  91267. }
  91268. // Empty node
  91269. if (!node.jointName) {
  91270. if (node.babylonNode) {
  91271. return node.babylonNode;
  91272. }
  91273. else if (lastNode === null) {
  91274. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91275. node.babylonNode = dummy;
  91276. lastNode = dummy;
  91277. }
  91278. }
  91279. if (lastNode !== null) {
  91280. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  91281. configureNodeFromMatrix(lastNode, node, parent);
  91282. }
  91283. else {
  91284. var translation = node.translation || [0, 0, 0];
  91285. var rotation = node.rotation || [0, 0, 0, 1];
  91286. var scale = node.scale || [1, 1, 1];
  91287. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  91288. }
  91289. lastNode.updateCache(true);
  91290. node.babylonNode = lastNode;
  91291. }
  91292. return lastNode;
  91293. };
  91294. /**
  91295. * Traverses nodes and creates them
  91296. */
  91297. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  91298. if (meshIncluded === void 0) { meshIncluded = false; }
  91299. var node = gltfRuntime.nodes[id];
  91300. var newNode = null;
  91301. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  91302. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  91303. meshIncluded = true;
  91304. }
  91305. else {
  91306. meshIncluded = false;
  91307. }
  91308. }
  91309. else {
  91310. meshIncluded = true;
  91311. }
  91312. if (!node.jointName && meshIncluded) {
  91313. newNode = importNode(gltfRuntime, node, id, parent);
  91314. if (newNode !== null) {
  91315. newNode.id = id;
  91316. newNode.parent = parent;
  91317. }
  91318. }
  91319. if (node.children) {
  91320. for (var i = 0; i < node.children.length; i++) {
  91321. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  91322. }
  91323. }
  91324. };
  91325. /**
  91326. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  91327. */
  91328. var postLoad = function (gltfRuntime) {
  91329. // Nodes
  91330. var currentScene = gltfRuntime.currentScene;
  91331. if (currentScene) {
  91332. for (var i = 0; i < currentScene.nodes.length; i++) {
  91333. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91334. }
  91335. }
  91336. else {
  91337. for (var thing in gltfRuntime.scenes) {
  91338. currentScene = gltfRuntime.scenes[thing];
  91339. for (var i = 0; i < currentScene.nodes.length; i++) {
  91340. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91341. }
  91342. }
  91343. }
  91344. // Set animations
  91345. loadAnimations(gltfRuntime);
  91346. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  91347. var skeleton = gltfRuntime.scene.skeletons[i];
  91348. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  91349. }
  91350. };
  91351. /**
  91352. * onBind shaderrs callback to set uniforms and matrices
  91353. */
  91354. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  91355. var materialValues = material.values || technique.parameters;
  91356. for (var unif in unTreatedUniforms) {
  91357. var uniform = unTreatedUniforms[unif];
  91358. var type = uniform.type;
  91359. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  91360. if (uniform.semantic && !uniform.source && !uniform.node) {
  91361. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  91362. }
  91363. else if (uniform.semantic && (uniform.source || uniform.node)) {
  91364. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  91365. if (source === null) {
  91366. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  91367. }
  91368. if (source === null) {
  91369. continue;
  91370. }
  91371. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  91372. }
  91373. }
  91374. else {
  91375. var value = materialValues[technique.uniforms[unif]];
  91376. if (!value) {
  91377. continue;
  91378. }
  91379. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91380. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  91381. if (texture === null || texture === undefined) {
  91382. continue;
  91383. }
  91384. shaderMaterial.getEffect().setTexture(unif, texture);
  91385. }
  91386. else {
  91387. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  91388. }
  91389. }
  91390. }
  91391. onSuccess(shaderMaterial);
  91392. };
  91393. /**
  91394. * Prepare uniforms to send the only one time
  91395. * Loads the appropriate textures
  91396. */
  91397. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  91398. var materialValues = material.values || technique.parameters;
  91399. var techniqueUniforms = technique.uniforms;
  91400. /**
  91401. * Prepare values here (not matrices)
  91402. */
  91403. for (var unif in unTreatedUniforms) {
  91404. var uniform = unTreatedUniforms[unif];
  91405. var type = uniform.type;
  91406. var value = materialValues[techniqueUniforms[unif]];
  91407. if (value === undefined) {
  91408. // In case the value is the same for all materials
  91409. value = uniform.value;
  91410. }
  91411. if (!value) {
  91412. continue;
  91413. }
  91414. var onLoadTexture = function (uniformName) {
  91415. return function (texture) {
  91416. if (uniform.value && uniformName) {
  91417. // Static uniform
  91418. shaderMaterial.setTexture(uniformName, texture);
  91419. delete unTreatedUniforms[uniformName];
  91420. }
  91421. };
  91422. };
  91423. // Texture (sampler2D)
  91424. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91425. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  91426. }
  91427. else {
  91428. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  91429. // Static uniform
  91430. delete unTreatedUniforms[unif];
  91431. }
  91432. }
  91433. }
  91434. };
  91435. /**
  91436. * Shader compilation failed
  91437. */
  91438. var onShaderCompileError = function (program, shaderMaterial, onError) {
  91439. return function (effect, error) {
  91440. shaderMaterial.dispose(true);
  91441. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  91442. };
  91443. };
  91444. /**
  91445. * Shader compilation success
  91446. */
  91447. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91448. return function (_) {
  91449. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91450. shaderMaterial.onBind = function (mesh) {
  91451. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91452. };
  91453. };
  91454. };
  91455. /**
  91456. * Returns the appropriate uniform if already handled by babylon
  91457. */
  91458. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91459. for (var unif in technique.uniforms) {
  91460. var uniform = technique.uniforms[unif];
  91461. var uniformParameter = technique.parameters[uniform];
  91462. if (tokenizer.currentIdentifier === unif) {
  91463. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91464. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91465. if (transformIndex !== -1) {
  91466. delete unTreatedUniforms[unif];
  91467. return babylonTransforms[transformIndex];
  91468. }
  91469. }
  91470. }
  91471. }
  91472. return tokenizer.currentIdentifier;
  91473. };
  91474. /**
  91475. * All shaders loaded. Create materials one by one
  91476. */
  91477. var importMaterials = function (gltfRuntime) {
  91478. // Create materials
  91479. for (var mat in gltfRuntime.materials) {
  91480. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91481. }
  91482. };
  91483. /**
  91484. * Implementation of the base glTF spec
  91485. */
  91486. var GLTFLoaderBase = /** @class */ (function () {
  91487. function GLTFLoaderBase() {
  91488. }
  91489. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91490. var gltfRuntime = {
  91491. extensions: {},
  91492. accessors: {},
  91493. buffers: {},
  91494. bufferViews: {},
  91495. meshes: {},
  91496. lights: {},
  91497. cameras: {},
  91498. nodes: {},
  91499. images: {},
  91500. textures: {},
  91501. shaders: {},
  91502. programs: {},
  91503. samplers: {},
  91504. techniques: {},
  91505. materials: {},
  91506. animations: {},
  91507. skins: {},
  91508. extensionsUsed: [],
  91509. scenes: {},
  91510. buffersCount: 0,
  91511. shaderscount: 0,
  91512. scene: scene,
  91513. rootUrl: rootUrl,
  91514. loadedBufferCount: 0,
  91515. loadedBufferViews: {},
  91516. loadedShaderCount: 0,
  91517. importOnlyMeshes: false,
  91518. dummyNodes: []
  91519. };
  91520. // Parse
  91521. if (parsedData.extensions) {
  91522. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91523. }
  91524. if (parsedData.extensionsUsed) {
  91525. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91526. }
  91527. if (parsedData.buffers) {
  91528. parseBuffers(parsedData.buffers, gltfRuntime);
  91529. }
  91530. if (parsedData.bufferViews) {
  91531. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91532. }
  91533. if (parsedData.accessors) {
  91534. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91535. }
  91536. if (parsedData.meshes) {
  91537. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91538. }
  91539. if (parsedData.lights) {
  91540. parseObject(parsedData.lights, "lights", gltfRuntime);
  91541. }
  91542. if (parsedData.cameras) {
  91543. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91544. }
  91545. if (parsedData.nodes) {
  91546. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91547. }
  91548. if (parsedData.images) {
  91549. parseObject(parsedData.images, "images", gltfRuntime);
  91550. }
  91551. if (parsedData.textures) {
  91552. parseObject(parsedData.textures, "textures", gltfRuntime);
  91553. }
  91554. if (parsedData.shaders) {
  91555. parseShaders(parsedData.shaders, gltfRuntime);
  91556. }
  91557. if (parsedData.programs) {
  91558. parseObject(parsedData.programs, "programs", gltfRuntime);
  91559. }
  91560. if (parsedData.samplers) {
  91561. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91562. }
  91563. if (parsedData.techniques) {
  91564. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91565. }
  91566. if (parsedData.materials) {
  91567. parseObject(parsedData.materials, "materials", gltfRuntime);
  91568. }
  91569. if (parsedData.animations) {
  91570. parseObject(parsedData.animations, "animations", gltfRuntime);
  91571. }
  91572. if (parsedData.skins) {
  91573. parseObject(parsedData.skins, "skins", gltfRuntime);
  91574. }
  91575. if (parsedData.scenes) {
  91576. gltfRuntime.scenes = parsedData.scenes;
  91577. }
  91578. if (parsedData.scene && parsedData.scenes) {
  91579. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91580. }
  91581. return gltfRuntime;
  91582. };
  91583. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91584. var buffer = gltfRuntime.buffers[id];
  91585. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91586. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91587. }
  91588. else {
  91589. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91590. if (request) {
  91591. onError(request.status + " " + request.statusText);
  91592. }
  91593. });
  91594. }
  91595. };
  91596. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91597. var texture = gltfRuntime.textures[id];
  91598. if (!texture || !texture.source) {
  91599. onError("");
  91600. return;
  91601. }
  91602. if (texture.babylonTexture) {
  91603. onSuccess(null);
  91604. return;
  91605. }
  91606. var source = gltfRuntime.images[texture.source];
  91607. if (BABYLON.Tools.IsBase64(source.uri)) {
  91608. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91609. }
  91610. else {
  91611. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91612. if (request) {
  91613. onError(request.status + " " + request.statusText);
  91614. }
  91615. });
  91616. }
  91617. };
  91618. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91619. var texture = gltfRuntime.textures[id];
  91620. if (texture.babylonTexture) {
  91621. onSuccess(texture.babylonTexture);
  91622. return;
  91623. }
  91624. var sampler = gltfRuntime.samplers[texture.sampler];
  91625. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91626. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91627. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91628. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91629. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91630. var blob = new Blob([buffer]);
  91631. var blobURL = URL.createObjectURL(blob);
  91632. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91633. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91634. if (sampler.wrapS !== undefined) {
  91635. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91636. }
  91637. if (sampler.wrapT !== undefined) {
  91638. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91639. }
  91640. newTexture.name = id;
  91641. texture.babylonTexture = newTexture;
  91642. onSuccess(newTexture);
  91643. };
  91644. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91645. var shader = gltfRuntime.shaders[id];
  91646. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91647. var shaderString = atob(shader.uri.split(",")[1]);
  91648. onSuccess(shaderString);
  91649. }
  91650. else {
  91651. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91652. if (request) {
  91653. onError(request.status + " " + request.statusText);
  91654. }
  91655. });
  91656. }
  91657. };
  91658. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91659. var material = gltfRuntime.materials[id];
  91660. if (!material.technique) {
  91661. if (onError) {
  91662. onError("No technique found.");
  91663. }
  91664. return;
  91665. }
  91666. var technique = gltfRuntime.techniques[material.technique];
  91667. if (!technique) {
  91668. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91669. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  91670. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91671. onSuccess(defaultMaterial);
  91672. return;
  91673. }
  91674. var program = gltfRuntime.programs[technique.program];
  91675. var states = technique.states;
  91676. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  91677. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  91678. var newVertexShader = "";
  91679. var newPixelShader = "";
  91680. var vertexTokenizer = new Tokenizer(vertexShader);
  91681. var pixelTokenizer = new Tokenizer(pixelShader);
  91682. var unTreatedUniforms = {};
  91683. var uniforms = [];
  91684. var attributes = [];
  91685. var samplers = [];
  91686. // Fill uniform, sampler2D and attributes
  91687. for (var unif in technique.uniforms) {
  91688. var uniform = technique.uniforms[unif];
  91689. var uniformParameter = technique.parameters[uniform];
  91690. unTreatedUniforms[unif] = uniformParameter;
  91691. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  91692. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91693. if (transformIndex !== -1) {
  91694. uniforms.push(babylonTransforms[transformIndex]);
  91695. delete unTreatedUniforms[unif];
  91696. }
  91697. else {
  91698. uniforms.push(unif);
  91699. }
  91700. }
  91701. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  91702. samplers.push(unif);
  91703. }
  91704. else {
  91705. uniforms.push(unif);
  91706. }
  91707. }
  91708. for (var attr in technique.attributes) {
  91709. var attribute = technique.attributes[attr];
  91710. var attributeParameter = technique.parameters[attribute];
  91711. if (attributeParameter.semantic) {
  91712. attributes.push(getAttribute(attributeParameter));
  91713. }
  91714. }
  91715. // Configure vertex shader
  91716. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  91717. var tokenType = vertexTokenizer.currentToken;
  91718. if (tokenType !== ETokenType.IDENTIFIER) {
  91719. newVertexShader += vertexTokenizer.currentString;
  91720. continue;
  91721. }
  91722. var foundAttribute = false;
  91723. for (var attr in technique.attributes) {
  91724. var attribute = technique.attributes[attr];
  91725. var attributeParameter = technique.parameters[attribute];
  91726. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  91727. newVertexShader += getAttribute(attributeParameter);
  91728. foundAttribute = true;
  91729. break;
  91730. }
  91731. }
  91732. if (foundAttribute) {
  91733. continue;
  91734. }
  91735. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  91736. }
  91737. // Configure pixel shader
  91738. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  91739. var tokenType = pixelTokenizer.currentToken;
  91740. if (tokenType !== ETokenType.IDENTIFIER) {
  91741. newPixelShader += pixelTokenizer.currentString;
  91742. continue;
  91743. }
  91744. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  91745. }
  91746. // Create shader material
  91747. var shaderPath = {
  91748. vertex: program.vertexShader + id,
  91749. fragment: program.fragmentShader + id
  91750. };
  91751. var options = {
  91752. attributes: attributes,
  91753. uniforms: uniforms,
  91754. samplers: samplers,
  91755. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  91756. };
  91757. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  91758. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  91759. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  91760. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  91761. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  91762. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91763. if (states && states.functions) {
  91764. var functions = states.functions;
  91765. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  91766. shaderMaterial.backFaceCulling = false;
  91767. }
  91768. var blendFunc = functions.blendFuncSeparate;
  91769. if (blendFunc) {
  91770. 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) {
  91771. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  91772. }
  91773. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91774. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91775. }
  91776. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91777. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  91778. }
  91779. 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) {
  91780. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  91781. }
  91782. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91783. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  91784. }
  91785. 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) {
  91786. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  91787. }
  91788. }
  91789. }
  91790. };
  91791. return GLTFLoaderBase;
  91792. }());
  91793. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  91794. /**
  91795. * glTF V1 Loader
  91796. */
  91797. var GLTFLoader = /** @class */ (function () {
  91798. function GLTFLoader() {
  91799. // #region Stubs for IGLTFLoader interface
  91800. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91801. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91802. this.compileMaterials = false;
  91803. this.useClipPlane = false;
  91804. this.compileShadowGenerators = false;
  91805. this.onDisposeObservable = new BABYLON.Observable();
  91806. this.onMeshLoadedObservable = new BABYLON.Observable();
  91807. this.onTextureLoadedObservable = new BABYLON.Observable();
  91808. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91809. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  91810. this.onCompleteObservable = new BABYLON.Observable();
  91811. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91812. this.state = null;
  91813. }
  91814. GLTFLoader.RegisterExtension = function (extension) {
  91815. if (GLTFLoader.Extensions[extension.name]) {
  91816. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  91817. return;
  91818. }
  91819. GLTFLoader.Extensions[extension.name] = extension;
  91820. };
  91821. GLTFLoader.prototype.dispose = function () { };
  91822. // #endregion
  91823. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  91824. var _this = this;
  91825. scene.useRightHandedSystem = true;
  91826. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91827. gltfRuntime.importOnlyMeshes = true;
  91828. if (meshesNames === "") {
  91829. gltfRuntime.importMeshesNames = [];
  91830. }
  91831. else if (typeof meshesNames === "string") {
  91832. gltfRuntime.importMeshesNames = [meshesNames];
  91833. }
  91834. else if (meshesNames && !(meshesNames instanceof Array)) {
  91835. gltfRuntime.importMeshesNames = [meshesNames];
  91836. }
  91837. else {
  91838. gltfRuntime.importMeshesNames = [];
  91839. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  91840. }
  91841. // Create nodes
  91842. _this._createNodes(gltfRuntime);
  91843. var meshes = new Array();
  91844. var skeletons = new Array();
  91845. // Fill arrays of meshes and skeletons
  91846. for (var nde in gltfRuntime.nodes) {
  91847. var node = gltfRuntime.nodes[nde];
  91848. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  91849. meshes.push(node.babylonNode);
  91850. }
  91851. }
  91852. for (var skl in gltfRuntime.skins) {
  91853. var skin = gltfRuntime.skins[skl];
  91854. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  91855. skeletons.push(skin.babylonSkeleton);
  91856. }
  91857. }
  91858. // Load buffers, shaders, materials, etc.
  91859. _this._loadBuffersAsync(gltfRuntime, function () {
  91860. _this._loadShadersAsync(gltfRuntime, function () {
  91861. importMaterials(gltfRuntime);
  91862. postLoad(gltfRuntime);
  91863. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91864. onSuccess(meshes, [], skeletons);
  91865. }
  91866. });
  91867. }, onProgress);
  91868. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91869. onSuccess(meshes, [], skeletons);
  91870. }
  91871. }, onError);
  91872. return true;
  91873. };
  91874. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91875. var _this = this;
  91876. return new Promise(function (resolve, reject) {
  91877. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  91878. resolve({
  91879. meshes: meshes,
  91880. particleSystems: particleSystems,
  91881. skeletons: skeletons
  91882. });
  91883. }, onProgress, function (message) {
  91884. reject(new Error(message));
  91885. });
  91886. });
  91887. };
  91888. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  91889. var _this = this;
  91890. scene.useRightHandedSystem = true;
  91891. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91892. // Load runtime extensios
  91893. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  91894. // Create nodes
  91895. _this._createNodes(gltfRuntime);
  91896. // Load buffers, shaders, materials, etc.
  91897. _this._loadBuffersAsync(gltfRuntime, function () {
  91898. _this._loadShadersAsync(gltfRuntime, function () {
  91899. importMaterials(gltfRuntime);
  91900. postLoad(gltfRuntime);
  91901. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  91902. onSuccess();
  91903. }
  91904. });
  91905. });
  91906. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  91907. onSuccess();
  91908. }
  91909. }, onError);
  91910. }, onError);
  91911. };
  91912. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91913. var _this = this;
  91914. return new Promise(function (resolve, reject) {
  91915. _this._loadAsync(scene, data, rootUrl, function () {
  91916. resolve();
  91917. }, onProgress, function (message) {
  91918. reject(new Error(message));
  91919. });
  91920. });
  91921. };
  91922. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  91923. var hasShaders = false;
  91924. var processShader = function (sha, shader) {
  91925. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  91926. gltfRuntime.loadedShaderCount++;
  91927. if (shaderString) {
  91928. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  91929. }
  91930. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  91931. onload();
  91932. }
  91933. }, function () {
  91934. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  91935. });
  91936. };
  91937. for (var sha in gltfRuntime.shaders) {
  91938. hasShaders = true;
  91939. var shader = gltfRuntime.shaders[sha];
  91940. if (shader) {
  91941. processShader.bind(this, sha, shader)();
  91942. }
  91943. else {
  91944. BABYLON.Tools.Error("No shader named: " + sha);
  91945. }
  91946. }
  91947. if (!hasShaders) {
  91948. onload();
  91949. }
  91950. };
  91951. ;
  91952. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  91953. var hasBuffers = false;
  91954. var processBuffer = function (buf, buffer) {
  91955. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  91956. gltfRuntime.loadedBufferCount++;
  91957. if (bufferView) {
  91958. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  91959. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  91960. }
  91961. gltfRuntime.loadedBufferViews[buf] = bufferView;
  91962. }
  91963. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  91964. onLoad();
  91965. }
  91966. }, function () {
  91967. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  91968. });
  91969. };
  91970. for (var buf in gltfRuntime.buffers) {
  91971. hasBuffers = true;
  91972. var buffer = gltfRuntime.buffers[buf];
  91973. if (buffer) {
  91974. processBuffer.bind(this, buf, buffer)();
  91975. }
  91976. else {
  91977. BABYLON.Tools.Error("No buffer named: " + buf);
  91978. }
  91979. }
  91980. if (!hasBuffers) {
  91981. onLoad();
  91982. }
  91983. };
  91984. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  91985. var currentScene = gltfRuntime.currentScene;
  91986. if (currentScene) {
  91987. // Only one scene even if multiple scenes are defined
  91988. for (var i = 0; i < currentScene.nodes.length; i++) {
  91989. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91990. }
  91991. }
  91992. else {
  91993. // Load all scenes
  91994. for (var thing in gltfRuntime.scenes) {
  91995. currentScene = gltfRuntime.scenes[thing];
  91996. for (var i = 0; i < currentScene.nodes.length; i++) {
  91997. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91998. }
  91999. }
  92000. }
  92001. };
  92002. GLTFLoader.Extensions = {};
  92003. return GLTFLoader;
  92004. }());
  92005. GLTF1.GLTFLoader = GLTFLoader;
  92006. ;
  92007. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  92008. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92009. })(BABYLON || (BABYLON = {}));
  92010. //# sourceMappingURL=babylon.glTFLoader.js.map
  92011. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92012. var BABYLON;
  92013. (function (BABYLON) {
  92014. var GLTF1;
  92015. (function (GLTF1) {
  92016. /**
  92017. * Utils functions for GLTF
  92018. */
  92019. var GLTFUtils = /** @class */ (function () {
  92020. function GLTFUtils() {
  92021. }
  92022. /**
  92023. * Sets the given "parameter" matrix
  92024. * @param scene: the {BABYLON.Scene} object
  92025. * @param source: the source node where to pick the matrix
  92026. * @param parameter: the GLTF technique parameter
  92027. * @param uniformName: the name of the shader's uniform
  92028. * @param shaderMaterial: the shader material
  92029. */
  92030. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  92031. var mat = null;
  92032. if (parameter.semantic === "MODEL") {
  92033. mat = source.getWorldMatrix();
  92034. }
  92035. else if (parameter.semantic === "PROJECTION") {
  92036. mat = scene.getProjectionMatrix();
  92037. }
  92038. else if (parameter.semantic === "VIEW") {
  92039. mat = scene.getViewMatrix();
  92040. }
  92041. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  92042. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  92043. }
  92044. else if (parameter.semantic === "MODELVIEW") {
  92045. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  92046. }
  92047. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  92048. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  92049. }
  92050. else if (parameter.semantic === "MODELINVERSE") {
  92051. mat = source.getWorldMatrix().invert();
  92052. }
  92053. else if (parameter.semantic === "VIEWINVERSE") {
  92054. mat = scene.getViewMatrix().invert();
  92055. }
  92056. else if (parameter.semantic === "PROJECTIONINVERSE") {
  92057. mat = scene.getProjectionMatrix().invert();
  92058. }
  92059. else if (parameter.semantic === "MODELVIEWINVERSE") {
  92060. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  92061. }
  92062. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  92063. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  92064. }
  92065. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  92066. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  92067. }
  92068. else {
  92069. debugger;
  92070. }
  92071. if (mat) {
  92072. switch (parameter.type) {
  92073. case GLTF1.EParameterType.FLOAT_MAT2:
  92074. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  92075. break;
  92076. case GLTF1.EParameterType.FLOAT_MAT3:
  92077. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  92078. break;
  92079. case GLTF1.EParameterType.FLOAT_MAT4:
  92080. shaderMaterial.setMatrix(uniformName, mat);
  92081. break;
  92082. default: break;
  92083. }
  92084. }
  92085. };
  92086. /**
  92087. * Sets the given "parameter" matrix
  92088. * @param shaderMaterial: the shader material
  92089. * @param uniform: the name of the shader's uniform
  92090. * @param value: the value of the uniform
  92091. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  92092. */
  92093. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  92094. switch (type) {
  92095. case GLTF1.EParameterType.FLOAT:
  92096. shaderMaterial.setFloat(uniform, value);
  92097. return true;
  92098. case GLTF1.EParameterType.FLOAT_VEC2:
  92099. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  92100. return true;
  92101. case GLTF1.EParameterType.FLOAT_VEC3:
  92102. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  92103. return true;
  92104. case GLTF1.EParameterType.FLOAT_VEC4:
  92105. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  92106. return true;
  92107. default: return false;
  92108. }
  92109. };
  92110. /**
  92111. * Returns the wrap mode of the texture
  92112. * @param mode: the mode value
  92113. */
  92114. GLTFUtils.GetWrapMode = function (mode) {
  92115. switch (mode) {
  92116. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92117. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92118. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92119. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92120. }
  92121. };
  92122. /**
  92123. * Returns the byte stride giving an accessor
  92124. * @param accessor: the GLTF accessor objet
  92125. */
  92126. GLTFUtils.GetByteStrideFromType = function (accessor) {
  92127. // Needs this function since "byteStride" isn't requiered in glTF format
  92128. var type = accessor.type;
  92129. switch (type) {
  92130. case "VEC2": return 2;
  92131. case "VEC3": return 3;
  92132. case "VEC4": return 4;
  92133. case "MAT2": return 4;
  92134. case "MAT3": return 9;
  92135. case "MAT4": return 16;
  92136. default: return 1;
  92137. }
  92138. };
  92139. /**
  92140. * Returns the texture filter mode giving a mode value
  92141. * @param mode: the filter mode value
  92142. */
  92143. GLTFUtils.GetTextureFilterMode = function (mode) {
  92144. switch (mode) {
  92145. case GLTF1.ETextureFilterType.LINEAR:
  92146. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  92147. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92148. case GLTF1.ETextureFilterType.NEAREST:
  92149. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  92150. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  92151. }
  92152. };
  92153. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  92154. var byteOffset = bufferView.byteOffset + byteOffset;
  92155. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  92156. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  92157. throw new Error("Buffer access is out of range");
  92158. }
  92159. var buffer = loadedBufferView.buffer;
  92160. byteOffset += loadedBufferView.byteOffset;
  92161. switch (componentType) {
  92162. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  92163. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  92164. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  92165. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  92166. default: return new Float32Array(buffer, byteOffset, byteLength);
  92167. }
  92168. };
  92169. /**
  92170. * Returns a buffer from its accessor
  92171. * @param gltfRuntime: the GLTF runtime
  92172. * @param accessor: the GLTF accessor
  92173. */
  92174. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  92175. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  92176. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  92177. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  92178. };
  92179. /**
  92180. * Decodes a buffer view into a string
  92181. * @param view: the buffer view
  92182. */
  92183. GLTFUtils.DecodeBufferToText = function (view) {
  92184. var result = "";
  92185. var length = view.byteLength;
  92186. for (var i = 0; i < length; ++i) {
  92187. result += String.fromCharCode(view[i]);
  92188. }
  92189. return result;
  92190. };
  92191. /**
  92192. * Returns the default material of gltf. Related to
  92193. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  92194. * @param scene: the Babylon.js scene
  92195. */
  92196. GLTFUtils.GetDefaultMaterial = function (scene) {
  92197. if (!GLTFUtils._DefaultMaterial) {
  92198. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  92199. "precision highp float;",
  92200. "",
  92201. "uniform mat4 worldView;",
  92202. "uniform mat4 projection;",
  92203. "",
  92204. "attribute vec3 position;",
  92205. "",
  92206. "void main(void)",
  92207. "{",
  92208. " gl_Position = projection * worldView * vec4(position, 1.0);",
  92209. "}"
  92210. ].join("\n");
  92211. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  92212. "precision highp float;",
  92213. "",
  92214. "uniform vec4 u_emission;",
  92215. "",
  92216. "void main(void)",
  92217. "{",
  92218. " gl_FragColor = u_emission;",
  92219. "}"
  92220. ].join("\n");
  92221. var shaderPath = {
  92222. vertex: "GLTFDefaultMaterial",
  92223. fragment: "GLTFDefaultMaterial"
  92224. };
  92225. var options = {
  92226. attributes: ["position"],
  92227. uniforms: ["worldView", "projection", "u_emission"],
  92228. samplers: new Array(),
  92229. needAlphaBlending: false
  92230. };
  92231. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  92232. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  92233. }
  92234. return GLTFUtils._DefaultMaterial;
  92235. };
  92236. // The GLTF default material
  92237. GLTFUtils._DefaultMaterial = null;
  92238. return GLTFUtils;
  92239. }());
  92240. GLTF1.GLTFUtils = GLTFUtils;
  92241. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92242. })(BABYLON || (BABYLON = {}));
  92243. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  92244. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92245. var BABYLON;
  92246. (function (BABYLON) {
  92247. var GLTF1;
  92248. (function (GLTF1) {
  92249. var GLTFLoaderExtension = /** @class */ (function () {
  92250. function GLTFLoaderExtension(name) {
  92251. this._name = name;
  92252. }
  92253. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  92254. get: function () {
  92255. return this._name;
  92256. },
  92257. enumerable: true,
  92258. configurable: true
  92259. });
  92260. /**
  92261. * Defines an override for loading the runtime
  92262. * Return true to stop further extensions from loading the runtime
  92263. */
  92264. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92265. return false;
  92266. };
  92267. /**
  92268. * Defines an onverride for creating gltf runtime
  92269. * Return true to stop further extensions from creating the runtime
  92270. */
  92271. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92272. return false;
  92273. };
  92274. /**
  92275. * Defines an override for loading buffers
  92276. * Return true to stop further extensions from loading this buffer
  92277. */
  92278. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92279. return false;
  92280. };
  92281. /**
  92282. * Defines an override for loading texture buffers
  92283. * Return true to stop further extensions from loading this texture data
  92284. */
  92285. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92286. return false;
  92287. };
  92288. /**
  92289. * Defines an override for creating textures
  92290. * Return true to stop further extensions from loading this texture
  92291. */
  92292. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92293. return false;
  92294. };
  92295. /**
  92296. * Defines an override for loading shader strings
  92297. * Return true to stop further extensions from loading this shader data
  92298. */
  92299. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92300. return false;
  92301. };
  92302. /**
  92303. * Defines an override for loading materials
  92304. * Return true to stop further extensions from loading this material
  92305. */
  92306. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92307. return false;
  92308. };
  92309. // ---------
  92310. // Utilities
  92311. // ---------
  92312. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92313. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92314. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  92315. }, function () {
  92316. setTimeout(function () {
  92317. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92318. });
  92319. });
  92320. };
  92321. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92322. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92323. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  92324. }, function () {
  92325. setTimeout(function () {
  92326. onSuccess();
  92327. });
  92328. });
  92329. };
  92330. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92331. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92332. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92333. }, function () {
  92334. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92335. });
  92336. };
  92337. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  92338. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  92339. };
  92340. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92341. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92342. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92343. }, function () {
  92344. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92345. });
  92346. };
  92347. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92348. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92349. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92350. }, function () {
  92351. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92352. });
  92353. };
  92354. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92355. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92356. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92357. }, function () {
  92358. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92359. });
  92360. };
  92361. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92362. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92363. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92364. }, function () {
  92365. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92366. });
  92367. };
  92368. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  92369. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  92370. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  92371. if (func(loaderExtension)) {
  92372. return;
  92373. }
  92374. }
  92375. defaultFunc();
  92376. };
  92377. return GLTFLoaderExtension;
  92378. }());
  92379. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  92380. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92381. })(BABYLON || (BABYLON = {}));
  92382. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92383. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92384. var BABYLON;
  92385. (function (BABYLON) {
  92386. var GLTF1;
  92387. (function (GLTF1) {
  92388. var BinaryExtensionBufferName = "binary_glTF";
  92389. ;
  92390. ;
  92391. var GLTFBinaryExtension = /** @class */ (function (_super) {
  92392. __extends(GLTFBinaryExtension, _super);
  92393. function GLTFBinaryExtension() {
  92394. return _super.call(this, "KHR_binary_glTF") || this;
  92395. }
  92396. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92397. var extensionsUsed = data.json.extensionsUsed;
  92398. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  92399. return false;
  92400. }
  92401. this._bin = data.bin;
  92402. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92403. return true;
  92404. };
  92405. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92406. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  92407. return false;
  92408. }
  92409. if (id !== BinaryExtensionBufferName) {
  92410. return false;
  92411. }
  92412. onSuccess(this._bin);
  92413. return true;
  92414. };
  92415. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92416. var texture = gltfRuntime.textures[id];
  92417. var source = gltfRuntime.images[texture.source];
  92418. if (!source.extensions || !(this.name in source.extensions)) {
  92419. return false;
  92420. }
  92421. var sourceExt = source.extensions[this.name];
  92422. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  92423. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92424. onSuccess(buffer);
  92425. return true;
  92426. };
  92427. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92428. var shader = gltfRuntime.shaders[id];
  92429. if (!shader.extensions || !(this.name in shader.extensions)) {
  92430. return false;
  92431. }
  92432. var binaryExtensionShader = shader.extensions[this.name];
  92433. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  92434. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92435. setTimeout(function () {
  92436. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  92437. onSuccess(shaderString);
  92438. });
  92439. return true;
  92440. };
  92441. return GLTFBinaryExtension;
  92442. }(GLTF1.GLTFLoaderExtension));
  92443. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  92444. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  92445. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92446. })(BABYLON || (BABYLON = {}));
  92447. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92448. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92449. var BABYLON;
  92450. (function (BABYLON) {
  92451. var GLTF1;
  92452. (function (GLTF1) {
  92453. ;
  92454. ;
  92455. ;
  92456. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92457. __extends(GLTFMaterialsCommonExtension, _super);
  92458. function GLTFMaterialsCommonExtension() {
  92459. return _super.call(this, "KHR_materials_common") || this;
  92460. }
  92461. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92462. if (!gltfRuntime.extensions)
  92463. return false;
  92464. var extension = gltfRuntime.extensions[this.name];
  92465. if (!extension)
  92466. return false;
  92467. // Create lights
  92468. var lights = extension.lights;
  92469. if (lights) {
  92470. for (var thing in lights) {
  92471. var light = lights[thing];
  92472. switch (light.type) {
  92473. case "ambient":
  92474. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92475. var ambient = light.ambient;
  92476. if (ambient) {
  92477. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92478. }
  92479. break;
  92480. case "point":
  92481. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92482. var point = light.point;
  92483. if (point) {
  92484. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92485. }
  92486. break;
  92487. case "directional":
  92488. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92489. var directional = light.directional;
  92490. if (directional) {
  92491. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92492. }
  92493. break;
  92494. case "spot":
  92495. var spot = light.spot;
  92496. if (spot) {
  92497. 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);
  92498. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92499. }
  92500. break;
  92501. default:
  92502. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92503. break;
  92504. }
  92505. }
  92506. }
  92507. return false;
  92508. };
  92509. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92510. var material = gltfRuntime.materials[id];
  92511. if (!material || !material.extensions)
  92512. return false;
  92513. var extension = material.extensions[this.name];
  92514. if (!extension)
  92515. return false;
  92516. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92517. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92518. if (extension.technique === "CONSTANT") {
  92519. standardMaterial.disableLighting = true;
  92520. }
  92521. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92522. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92523. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92524. // Ambient
  92525. if (typeof extension.values.ambient === "string") {
  92526. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92527. }
  92528. else {
  92529. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92530. }
  92531. // Diffuse
  92532. if (typeof extension.values.diffuse === "string") {
  92533. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92534. }
  92535. else {
  92536. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92537. }
  92538. // Emission
  92539. if (typeof extension.values.emission === "string") {
  92540. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92541. }
  92542. else {
  92543. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92544. }
  92545. // Specular
  92546. if (typeof extension.values.specular === "string") {
  92547. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92548. }
  92549. else {
  92550. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92551. }
  92552. return true;
  92553. };
  92554. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92555. // Create buffer from texture url
  92556. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92557. // Create texture from buffer
  92558. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92559. }, onError);
  92560. };
  92561. return GLTFMaterialsCommonExtension;
  92562. }(GLTF1.GLTFLoaderExtension));
  92563. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92564. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92565. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92566. })(BABYLON || (BABYLON = {}));
  92567. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92568. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92569. var BABYLON;
  92570. (function (BABYLON) {
  92571. var GLTF2;
  92572. (function (GLTF2) {
  92573. var ArrayItem = /** @class */ (function () {
  92574. function ArrayItem() {
  92575. }
  92576. ArrayItem.Assign = function (values) {
  92577. if (values) {
  92578. for (var index = 0; index < values.length; index++) {
  92579. values[index]._index = index;
  92580. }
  92581. }
  92582. };
  92583. return ArrayItem;
  92584. }());
  92585. GLTF2.ArrayItem = ArrayItem;
  92586. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92587. })(BABYLON || (BABYLON = {}));
  92588. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92589. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92590. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92591. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92592. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92593. var BABYLON;
  92594. (function (BABYLON) {
  92595. var GLTF2;
  92596. (function (GLTF2) {
  92597. var GLTFLoader = /** @class */ (function () {
  92598. function GLTFLoader() {
  92599. this._completePromises = new Array();
  92600. this._disposed = false;
  92601. this._state = null;
  92602. this._extensions = {};
  92603. this._defaultSampler = {};
  92604. this._requests = new Array();
  92605. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92606. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92607. this.compileMaterials = false;
  92608. this.useClipPlane = false;
  92609. this.compileShadowGenerators = false;
  92610. this.onDisposeObservable = new BABYLON.Observable();
  92611. this.onMeshLoadedObservable = new BABYLON.Observable();
  92612. this.onTextureLoadedObservable = new BABYLON.Observable();
  92613. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92614. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92615. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92616. this.onCompleteObservable = new BABYLON.Observable();
  92617. }
  92618. GLTFLoader._Register = function (name, factory) {
  92619. if (GLTFLoader._Factories[name]) {
  92620. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92621. return;
  92622. }
  92623. GLTFLoader._Factories[name] = factory;
  92624. // Keep the order of registration so that extensions registered first are called first.
  92625. GLTFLoader._Names.push(name);
  92626. };
  92627. Object.defineProperty(GLTFLoader.prototype, "state", {
  92628. get: function () {
  92629. return this._state;
  92630. },
  92631. enumerable: true,
  92632. configurable: true
  92633. });
  92634. GLTFLoader.prototype.dispose = function () {
  92635. if (this._disposed) {
  92636. return;
  92637. }
  92638. this._disposed = true;
  92639. this.onDisposeObservable.notifyObservers(this);
  92640. this.onDisposeObservable.clear();
  92641. this._clear();
  92642. };
  92643. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92644. var _this = this;
  92645. return Promise.resolve().then(function () {
  92646. var nodes = null;
  92647. if (meshesNames) {
  92648. var nodeMap_1 = {};
  92649. if (_this._gltf.nodes) {
  92650. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92651. var node = _a[_i];
  92652. if (node.name) {
  92653. nodeMap_1[node.name] = node;
  92654. }
  92655. }
  92656. }
  92657. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92658. nodes = names.map(function (name) {
  92659. var node = nodeMap_1[name];
  92660. if (!node) {
  92661. throw new Error("Failed to find node '" + name + "'");
  92662. }
  92663. return node;
  92664. });
  92665. }
  92666. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  92667. return {
  92668. meshes: _this._getMeshes(),
  92669. particleSystems: [],
  92670. skeletons: _this._getSkeletons(),
  92671. };
  92672. });
  92673. });
  92674. };
  92675. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92676. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  92677. };
  92678. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  92679. var _this = this;
  92680. return Promise.resolve().then(function () {
  92681. _this._loadExtensions();
  92682. _this._babylonScene = scene;
  92683. _this._rootUrl = rootUrl;
  92684. _this._progressCallback = onProgress;
  92685. _this._state = BABYLON.GLTFLoaderState.Loading;
  92686. _this._loadData(data);
  92687. _this._checkExtensions();
  92688. var promises = new Array();
  92689. if (nodes) {
  92690. promises.push(_this._loadNodesAsync(nodes));
  92691. }
  92692. else {
  92693. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  92694. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  92695. }
  92696. if (_this.compileMaterials) {
  92697. promises.push(_this._compileMaterialsAsync());
  92698. }
  92699. if (_this.compileShadowGenerators) {
  92700. promises.push(_this._compileShadowGeneratorsAsync());
  92701. }
  92702. var resultPromise = Promise.all(promises).then(function () {
  92703. _this._state = BABYLON.GLTFLoaderState.Ready;
  92704. _this._startAnimations();
  92705. });
  92706. resultPromise.then(function () {
  92707. _this._rootBabylonMesh.setEnabled(true);
  92708. BABYLON.Tools.SetImmediate(function () {
  92709. if (!_this._disposed) {
  92710. Promise.all(_this._completePromises).then(function () {
  92711. _this._state = BABYLON.GLTFLoaderState.Complete;
  92712. _this.onCompleteObservable.notifyObservers(_this);
  92713. _this.onCompleteObservable.clear();
  92714. _this._clear();
  92715. }).catch(function (error) {
  92716. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92717. _this._clear();
  92718. });
  92719. }
  92720. });
  92721. });
  92722. return resultPromise;
  92723. }).catch(function (error) {
  92724. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92725. _this._clear();
  92726. throw error;
  92727. });
  92728. };
  92729. GLTFLoader.prototype._loadExtensions = function () {
  92730. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92731. var name_1 = _a[_i];
  92732. var extension = GLTFLoader._Factories[name_1](this);
  92733. this._extensions[name_1] = extension;
  92734. this.onExtensionLoadedObservable.notifyObservers(extension);
  92735. }
  92736. this.onExtensionLoadedObservable.clear();
  92737. };
  92738. GLTFLoader.prototype._loadData = function (data) {
  92739. this._gltf = data.json;
  92740. this._setupData();
  92741. if (data.bin) {
  92742. var buffers = this._gltf.buffers;
  92743. if (buffers && buffers[0] && !buffers[0].uri) {
  92744. var binaryBuffer = buffers[0];
  92745. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  92746. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  92747. }
  92748. binaryBuffer._data = Promise.resolve(data.bin);
  92749. }
  92750. else {
  92751. BABYLON.Tools.Warn("Unexpected BIN chunk");
  92752. }
  92753. }
  92754. };
  92755. GLTFLoader.prototype._setupData = function () {
  92756. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  92757. GLTF2.ArrayItem.Assign(this._gltf.animations);
  92758. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  92759. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  92760. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  92761. GLTF2.ArrayItem.Assign(this._gltf.images);
  92762. GLTF2.ArrayItem.Assign(this._gltf.materials);
  92763. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  92764. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  92765. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  92766. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  92767. GLTF2.ArrayItem.Assign(this._gltf.skins);
  92768. GLTF2.ArrayItem.Assign(this._gltf.textures);
  92769. if (this._gltf.nodes) {
  92770. var nodeParents = {};
  92771. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  92772. var node = _a[_i];
  92773. if (node.children) {
  92774. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  92775. var index = _c[_b];
  92776. nodeParents[index] = node._index;
  92777. }
  92778. }
  92779. }
  92780. var rootNode = this._createRootNode();
  92781. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  92782. var node = _e[_d];
  92783. var parentIndex = nodeParents[node._index];
  92784. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  92785. }
  92786. }
  92787. };
  92788. GLTFLoader.prototype._checkExtensions = function () {
  92789. if (this._gltf.extensionsRequired) {
  92790. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  92791. var name_2 = _a[_i];
  92792. var extension = this._extensions[name_2];
  92793. if (!extension || !extension.enabled) {
  92794. throw new Error("Require extension " + name_2 + " is not available");
  92795. }
  92796. }
  92797. }
  92798. };
  92799. GLTFLoader.prototype._createRootNode = function () {
  92800. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  92801. this._rootBabylonMesh.setEnabled(false);
  92802. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  92803. switch (this.coordinateSystemMode) {
  92804. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  92805. if (!this._babylonScene.useRightHandedSystem) {
  92806. rootNode.rotation = [0, 1, 0, 0];
  92807. rootNode.scale = [1, 1, -1];
  92808. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  92809. }
  92810. break;
  92811. }
  92812. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  92813. this._babylonScene.useRightHandedSystem = true;
  92814. break;
  92815. }
  92816. default: {
  92817. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  92818. }
  92819. }
  92820. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  92821. return rootNode;
  92822. };
  92823. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  92824. var promises = new Array();
  92825. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  92826. var node = nodes_1[_i];
  92827. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92828. }
  92829. promises.push(this._loadAnimationsAsync());
  92830. return Promise.all(promises).then(function () { });
  92831. };
  92832. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  92833. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  92834. if (promise) {
  92835. return promise;
  92836. }
  92837. var promises = new Array();
  92838. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  92839. var index = _a[_i];
  92840. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  92841. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92842. }
  92843. promises.push(this._loadAnimationsAsync());
  92844. return Promise.all(promises).then(function () { });
  92845. };
  92846. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  92847. if (node._babylonMesh) {
  92848. callback(node._babylonMesh);
  92849. }
  92850. if (node._primitiveBabylonMeshes) {
  92851. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92852. var babylonMesh = _a[_i];
  92853. callback(babylonMesh);
  92854. }
  92855. }
  92856. };
  92857. GLTFLoader.prototype._getMeshes = function () {
  92858. var meshes = new Array();
  92859. // Root mesh is always first.
  92860. meshes.push(this._rootBabylonMesh);
  92861. var nodes = this._gltf.nodes;
  92862. if (nodes) {
  92863. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  92864. var node = nodes_2[_i];
  92865. this._forEachNodeMesh(node, function (mesh) {
  92866. meshes.push(mesh);
  92867. });
  92868. }
  92869. }
  92870. return meshes;
  92871. };
  92872. GLTFLoader.prototype._getSkeletons = function () {
  92873. var skeletons = new Array();
  92874. var skins = this._gltf.skins;
  92875. if (skins) {
  92876. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  92877. var skin = skins_1[_i];
  92878. if (skin._babylonSkeleton) {
  92879. skeletons.push(skin._babylonSkeleton);
  92880. }
  92881. }
  92882. }
  92883. return skeletons;
  92884. };
  92885. GLTFLoader.prototype._startAnimations = function () {
  92886. var animations = this._gltf.animations;
  92887. if (!animations) {
  92888. return;
  92889. }
  92890. switch (this.animationStartMode) {
  92891. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  92892. // do nothing
  92893. break;
  92894. }
  92895. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  92896. var animation = animations[0];
  92897. animation._babylonAnimationGroup.start(true);
  92898. break;
  92899. }
  92900. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  92901. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  92902. var animation = animations_1[_i];
  92903. animation._babylonAnimationGroup.start(true);
  92904. }
  92905. break;
  92906. }
  92907. default: {
  92908. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  92909. return;
  92910. }
  92911. }
  92912. };
  92913. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  92914. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  92915. if (promise) {
  92916. return promise;
  92917. }
  92918. if (node._babylonMesh) {
  92919. throw new Error(context + ": Invalid recursive node hierarchy");
  92920. }
  92921. var promises = new Array();
  92922. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  92923. node._babylonMesh = babylonMesh;
  92924. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92925. node._babylonAnimationTargets.push(babylonMesh);
  92926. GLTFLoader._LoadTransform(node, babylonMesh);
  92927. if (node.mesh != undefined) {
  92928. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  92929. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  92930. }
  92931. if (node.children) {
  92932. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  92933. var index = _a[_i];
  92934. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  92935. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  92936. }
  92937. }
  92938. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92939. return Promise.all(promises).then(function () { });
  92940. };
  92941. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  92942. // TODO: instancing
  92943. var _this = this;
  92944. var promises = new Array();
  92945. var primitives = mesh.primitives;
  92946. if (!primitives || primitives.length === 0) {
  92947. throw new Error(context + ": Primitives are missing");
  92948. }
  92949. GLTF2.ArrayItem.Assign(primitives);
  92950. if (primitives.length === 1) {
  92951. var primitive = primitives[0];
  92952. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  92953. }
  92954. else {
  92955. node._primitiveBabylonMeshes = [];
  92956. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  92957. var primitive = primitives_1[_i];
  92958. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  92959. node._primitiveBabylonMeshes.push(babylonMesh);
  92960. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  92961. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92962. }
  92963. }
  92964. if (node.skin != undefined) {
  92965. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  92966. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  92967. }
  92968. return Promise.all(promises).then(function () {
  92969. _this._forEachNodeMesh(node, function (babylonMesh) {
  92970. babylonMesh._refreshBoundingInfo(true);
  92971. });
  92972. });
  92973. };
  92974. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  92975. var _this = this;
  92976. var promises = new Array();
  92977. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  92978. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  92979. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  92980. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  92981. }));
  92982. if (primitive.material == undefined) {
  92983. babylonMesh.material = this._getDefaultMaterial();
  92984. }
  92985. else {
  92986. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  92987. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  92988. babylonMesh.material = babylonMaterial;
  92989. }));
  92990. }
  92991. return Promise.all(promises).then(function () { });
  92992. };
  92993. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  92994. var _this = this;
  92995. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  92996. if (promise) {
  92997. return promise;
  92998. }
  92999. var attributes = primitive.attributes;
  93000. if (!attributes) {
  93001. throw new Error(context + ": Attributes are missing");
  93002. }
  93003. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  93004. // TODO: handle other primitive modes
  93005. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  93006. }
  93007. var promises = new Array();
  93008. var babylonVertexData = new BABYLON.VertexData();
  93009. if (primitive.indices == undefined) {
  93010. var positionAccessorIndex = attributes["POSITION"];
  93011. if (positionAccessorIndex != undefined) {
  93012. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  93013. babylonVertexData.indices = new Uint32Array(accessor.count);
  93014. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  93015. babylonVertexData.indices[i] = i;
  93016. }
  93017. }
  93018. }
  93019. else {
  93020. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  93021. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  93022. babylonVertexData.indices = data;
  93023. }));
  93024. }
  93025. var loadAttribute = function (attribute, kind) {
  93026. if (attributes[attribute] == undefined) {
  93027. return;
  93028. }
  93029. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93030. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93031. babylonMesh._delayInfo.push(kind);
  93032. }
  93033. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93034. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93035. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  93036. if (attribute === "COLOR_0") {
  93037. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  93038. babylonMesh.hasVertexAlpha = true;
  93039. if (accessor.type === "VEC3") {
  93040. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  93041. }
  93042. }
  93043. babylonVertexData.set(attributeData, kind);
  93044. }));
  93045. };
  93046. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93047. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93048. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93049. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93050. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93051. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93052. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93053. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93054. return Promise.all(promises).then(function () {
  93055. return babylonVertexData;
  93056. });
  93057. };
  93058. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  93059. if (!primitive.targets) {
  93060. return;
  93061. }
  93062. if (node._numMorphTargets == undefined) {
  93063. node._numMorphTargets = primitive.targets.length;
  93064. }
  93065. else if (primitive.targets.length !== node._numMorphTargets) {
  93066. throw new Error(context + ": Primitives do not have the same number of targets");
  93067. }
  93068. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  93069. for (var index = 0; index < primitive.targets.length; index++) {
  93070. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  93071. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  93072. // TODO: tell the target whether it has positions, normals, tangents
  93073. }
  93074. };
  93075. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  93076. if (!primitive.targets) {
  93077. return Promise.resolve();
  93078. }
  93079. var promises = new Array();
  93080. var morphTargetManager = babylonMesh.morphTargetManager;
  93081. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  93082. var babylonMorphTarget = morphTargetManager.getTarget(index);
  93083. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  93084. }
  93085. return Promise.all(promises).then(function () { });
  93086. };
  93087. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  93088. var _this = this;
  93089. var promises = new Array();
  93090. var loadAttribute = function (attribute, setData) {
  93091. if (attributes[attribute] == undefined) {
  93092. return;
  93093. }
  93094. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93095. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93096. setData(data);
  93097. }));
  93098. };
  93099. loadAttribute("POSITION", function (data) {
  93100. if (babylonVertexData.positions) {
  93101. for (var i = 0; i < data.length; i++) {
  93102. data[i] += babylonVertexData.positions[i];
  93103. }
  93104. babylonMorphTarget.setPositions(data);
  93105. }
  93106. });
  93107. loadAttribute("NORMAL", function (data) {
  93108. if (babylonVertexData.normals) {
  93109. for (var i = 0; i < data.length; i++) {
  93110. data[i] += babylonVertexData.normals[i];
  93111. }
  93112. babylonMorphTarget.setNormals(data);
  93113. }
  93114. });
  93115. loadAttribute("TANGENT", function (data) {
  93116. if (babylonVertexData.tangents) {
  93117. // Tangent data for morph targets is stored as xyz delta.
  93118. // The vertexData.tangent is stored as xyzw.
  93119. // So we need to skip every fourth vertexData.tangent.
  93120. for (var i = 0, j = 0; i < data.length; i++) {
  93121. data[i] += babylonVertexData.tangents[j++];
  93122. if ((i + 1) % 3 == 0) {
  93123. j++;
  93124. }
  93125. }
  93126. babylonMorphTarget.setTangents(data);
  93127. }
  93128. });
  93129. return Promise.all(promises).then(function () { });
  93130. };
  93131. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  93132. if (accessor.componentType == 5126 /* FLOAT */) {
  93133. return data;
  93134. }
  93135. var factor = 1;
  93136. if (accessor.normalized) {
  93137. switch (accessor.componentType) {
  93138. case 5121 /* UNSIGNED_BYTE */: {
  93139. factor = 1 / 255;
  93140. break;
  93141. }
  93142. case 5123 /* UNSIGNED_SHORT */: {
  93143. factor = 1 / 65535;
  93144. break;
  93145. }
  93146. default: {
  93147. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93148. }
  93149. }
  93150. }
  93151. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  93152. for (var i = 0; i < result.length; i++) {
  93153. result[i] = data[i] * factor;
  93154. }
  93155. return result;
  93156. };
  93157. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  93158. var result = new Float32Array(data.length / 3 * 4);
  93159. var offset = 0;
  93160. for (var i = 0; i < result.length; i++) {
  93161. if ((i + 1) % 4 === 0) {
  93162. result[i] = 1;
  93163. }
  93164. else {
  93165. result[i] = data[offset++];
  93166. }
  93167. }
  93168. return result;
  93169. };
  93170. GLTFLoader._LoadTransform = function (node, babylonNode) {
  93171. var position = BABYLON.Vector3.Zero();
  93172. var rotation = BABYLON.Quaternion.Identity();
  93173. var scaling = BABYLON.Vector3.One();
  93174. if (node.matrix) {
  93175. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  93176. matrix.decompose(scaling, rotation, position);
  93177. }
  93178. else {
  93179. if (node.translation)
  93180. position = BABYLON.Vector3.FromArray(node.translation);
  93181. if (node.rotation)
  93182. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  93183. if (node.scale)
  93184. scaling = BABYLON.Vector3.FromArray(node.scale);
  93185. }
  93186. babylonNode.position = position;
  93187. babylonNode.rotationQuaternion = rotation;
  93188. babylonNode.scaling = scaling;
  93189. };
  93190. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  93191. var _this = this;
  93192. var assignSkeleton = function () {
  93193. _this._forEachNodeMesh(node, function (babylonMesh) {
  93194. babylonMesh.skeleton = skin._babylonSkeleton;
  93195. });
  93196. node._babylonMesh.parent = _this._rootBabylonMesh;
  93197. node._babylonMesh.position = BABYLON.Vector3.Zero();
  93198. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  93199. node._babylonMesh.scaling = BABYLON.Vector3.One();
  93200. };
  93201. if (skin._loaded) {
  93202. return skin._loaded.then(function () {
  93203. assignSkeleton();
  93204. });
  93205. }
  93206. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  93207. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  93208. var skeletonId = "skeleton" + skin._index;
  93209. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  93210. skin._babylonSkeleton = babylonSkeleton;
  93211. _this._loadBones(context, skin, inverseBindMatricesData);
  93212. assignSkeleton();
  93213. }));
  93214. };
  93215. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  93216. if (skin.inverseBindMatrices == undefined) {
  93217. return Promise.resolve(null);
  93218. }
  93219. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  93220. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93221. return data;
  93222. });
  93223. };
  93224. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  93225. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  93226. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93227. node._babylonAnimationTargets.push(babylonBone);
  93228. return babylonBone;
  93229. };
  93230. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  93231. var babylonBones = {};
  93232. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  93233. var index = _a[_i];
  93234. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  93235. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  93236. }
  93237. };
  93238. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  93239. var babylonBone = babylonBones[node._index];
  93240. if (babylonBone) {
  93241. return babylonBone;
  93242. }
  93243. var boneIndex = skin.joints.indexOf(node._index);
  93244. var baseMatrix = BABYLON.Matrix.Identity();
  93245. if (inverseBindMatricesData && boneIndex !== -1) {
  93246. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  93247. baseMatrix.invertToRef(baseMatrix);
  93248. }
  93249. var babylonParentBone = null;
  93250. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  93251. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  93252. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  93253. }
  93254. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  93255. babylonBones[node._index] = babylonBone;
  93256. return babylonBone;
  93257. };
  93258. GLTFLoader.prototype._getNodeMatrix = function (node) {
  93259. return node.matrix ?
  93260. BABYLON.Matrix.FromArray(node.matrix) :
  93261. 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());
  93262. };
  93263. GLTFLoader.prototype._loadAnimationsAsync = function () {
  93264. var animations = this._gltf.animations;
  93265. if (!animations) {
  93266. return Promise.resolve();
  93267. }
  93268. var promises = new Array();
  93269. for (var index = 0; index < animations.length; index++) {
  93270. var animation = animations[index];
  93271. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  93272. }
  93273. return Promise.all(promises).then(function () { });
  93274. };
  93275. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  93276. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  93277. animation._babylonAnimationGroup = babylonAnimationGroup;
  93278. var promises = new Array();
  93279. GLTF2.ArrayItem.Assign(animation.channels);
  93280. GLTF2.ArrayItem.Assign(animation.samplers);
  93281. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  93282. var channel = _a[_i];
  93283. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  93284. }
  93285. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  93286. return Promise.all(promises).then(function () {
  93287. babylonAnimationGroup.normalize();
  93288. });
  93289. };
  93290. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  93291. var _this = this;
  93292. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  93293. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  93294. return Promise.resolve();
  93295. }
  93296. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  93297. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  93298. var targetPath;
  93299. var animationType;
  93300. switch (channel.target.path) {
  93301. case "translation" /* TRANSLATION */: {
  93302. targetPath = "position";
  93303. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93304. break;
  93305. }
  93306. case "rotation" /* ROTATION */: {
  93307. targetPath = "rotationQuaternion";
  93308. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  93309. break;
  93310. }
  93311. case "scale" /* SCALE */: {
  93312. targetPath = "scaling";
  93313. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93314. break;
  93315. }
  93316. case "weights" /* WEIGHTS */: {
  93317. targetPath = "influence";
  93318. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  93319. break;
  93320. }
  93321. default: {
  93322. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  93323. }
  93324. }
  93325. var outputBufferOffset = 0;
  93326. var getNextOutputValue;
  93327. switch (targetPath) {
  93328. case "position": {
  93329. getNextOutputValue = function () {
  93330. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93331. outputBufferOffset += 3;
  93332. return value;
  93333. };
  93334. break;
  93335. }
  93336. case "rotationQuaternion": {
  93337. getNextOutputValue = function () {
  93338. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  93339. outputBufferOffset += 4;
  93340. return value;
  93341. };
  93342. break;
  93343. }
  93344. case "scaling": {
  93345. getNextOutputValue = function () {
  93346. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93347. outputBufferOffset += 3;
  93348. return value;
  93349. };
  93350. break;
  93351. }
  93352. case "influence": {
  93353. getNextOutputValue = function () {
  93354. var value = new Array(targetNode._numMorphTargets);
  93355. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  93356. value[i] = data.output[outputBufferOffset++];
  93357. }
  93358. return value;
  93359. };
  93360. break;
  93361. }
  93362. }
  93363. var getNextKey;
  93364. switch (data.interpolation) {
  93365. case "STEP" /* STEP */: {
  93366. getNextKey = function (frameIndex) { return ({
  93367. frame: data.input[frameIndex],
  93368. value: getNextOutputValue(),
  93369. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  93370. }); };
  93371. break;
  93372. }
  93373. case "LINEAR" /* LINEAR */: {
  93374. getNextKey = function (frameIndex) { return ({
  93375. frame: data.input[frameIndex],
  93376. value: getNextOutputValue()
  93377. }); };
  93378. break;
  93379. }
  93380. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93381. getNextKey = function (frameIndex) { return ({
  93382. frame: data.input[frameIndex],
  93383. inTangent: getNextOutputValue(),
  93384. value: getNextOutputValue(),
  93385. outTangent: getNextOutputValue()
  93386. }); };
  93387. break;
  93388. }
  93389. }
  93390. var keys;
  93391. if (data.input.length === 1) {
  93392. var key = getNextKey(0);
  93393. keys = [
  93394. { frame: key.frame, value: key.value },
  93395. { frame: key.frame + 1, value: key.value }
  93396. ];
  93397. }
  93398. else {
  93399. keys = new Array(data.input.length);
  93400. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  93401. keys[frameIndex] = getNextKey(frameIndex);
  93402. }
  93403. }
  93404. if (targetPath === "influence") {
  93405. var _loop_1 = function (targetIndex) {
  93406. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93407. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93408. babylonAnimation.setKeys(keys.map(function (key) { return ({
  93409. frame: key.frame,
  93410. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  93411. value: key.value[targetIndex],
  93412. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  93413. }); }));
  93414. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  93415. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  93416. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  93417. });
  93418. };
  93419. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  93420. _loop_1(targetIndex);
  93421. }
  93422. }
  93423. else {
  93424. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93425. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93426. babylonAnimation.setKeys(keys);
  93427. if (targetNode._babylonAnimationTargets) {
  93428. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  93429. var target = _a[_i];
  93430. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  93431. }
  93432. }
  93433. }
  93434. });
  93435. };
  93436. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  93437. if (sampler._data) {
  93438. return sampler._data;
  93439. }
  93440. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  93441. switch (interpolation) {
  93442. case "STEP" /* STEP */:
  93443. case "LINEAR" /* LINEAR */:
  93444. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93445. break;
  93446. }
  93447. default: {
  93448. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  93449. }
  93450. }
  93451. var inputData;
  93452. var outputData;
  93453. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  93454. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  93455. sampler._data = Promise.all([
  93456. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  93457. inputData = data;
  93458. }),
  93459. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  93460. outputData = data;
  93461. })
  93462. ]).then(function () {
  93463. return {
  93464. input: inputData,
  93465. interpolation: interpolation,
  93466. output: outputData,
  93467. };
  93468. });
  93469. return sampler._data;
  93470. };
  93471. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93472. if (buffer._data) {
  93473. return buffer._data;
  93474. }
  93475. if (!buffer.uri) {
  93476. throw new Error(context + ": Uri is missing");
  93477. }
  93478. buffer._data = this._loadUriAsync(context, buffer.uri);
  93479. return buffer._data;
  93480. };
  93481. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93482. if (bufferView._data) {
  93483. return bufferView._data;
  93484. }
  93485. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93486. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93487. try {
  93488. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93489. }
  93490. catch (e) {
  93491. throw new Error(context + ": " + e.message);
  93492. }
  93493. });
  93494. return bufferView._data;
  93495. };
  93496. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93497. var _this = this;
  93498. if (accessor.sparse) {
  93499. throw new Error(context + ": Sparse accessors are not currently supported");
  93500. }
  93501. if (accessor._data) {
  93502. return accessor._data;
  93503. }
  93504. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93505. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93506. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93507. var byteOffset = accessor.byteOffset || 0;
  93508. var byteStride = bufferView.byteStride;
  93509. if (byteStride === 0) {
  93510. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93511. }
  93512. try {
  93513. switch (accessor.componentType) {
  93514. case 5120 /* BYTE */: {
  93515. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93516. }
  93517. case 5121 /* UNSIGNED_BYTE */: {
  93518. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93519. }
  93520. case 5122 /* SHORT */: {
  93521. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93522. }
  93523. case 5123 /* UNSIGNED_SHORT */: {
  93524. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93525. }
  93526. case 5125 /* UNSIGNED_INT */: {
  93527. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93528. }
  93529. case 5126 /* FLOAT */: {
  93530. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93531. }
  93532. default: {
  93533. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93534. }
  93535. }
  93536. }
  93537. catch (e) {
  93538. throw new Error(context + ": " + e.messsage);
  93539. }
  93540. });
  93541. return accessor._data;
  93542. };
  93543. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93544. byteOffset += data.byteOffset;
  93545. var targetLength = count * numComponents;
  93546. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93547. return new typedArray(data.buffer, byteOffset, targetLength);
  93548. }
  93549. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93550. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93551. var targetBuffer = new typedArray(targetLength);
  93552. var sourceIndex = 0;
  93553. var targetIndex = 0;
  93554. while (targetIndex < targetLength) {
  93555. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93556. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93557. targetIndex++;
  93558. }
  93559. sourceIndex += elementStride;
  93560. }
  93561. return targetBuffer;
  93562. };
  93563. GLTFLoader.prototype._getDefaultMaterial = function () {
  93564. var id = "__gltf_default";
  93565. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93566. if (!babylonMaterial) {
  93567. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93568. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93569. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93570. babylonMaterial.metallic = 1;
  93571. babylonMaterial.roughness = 1;
  93572. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93573. }
  93574. return babylonMaterial;
  93575. };
  93576. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93577. var promises = new Array();
  93578. var babylonMaterial = material._babylonMaterial;
  93579. // Ensure metallic workflow
  93580. babylonMaterial.metallic = 1;
  93581. babylonMaterial.roughness = 1;
  93582. var properties = material.pbrMetallicRoughness;
  93583. if (properties) {
  93584. if (properties.baseColorFactor) {
  93585. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93586. babylonMaterial.alpha = properties.baseColorFactor[3];
  93587. }
  93588. else {
  93589. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93590. }
  93591. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93592. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93593. if (properties.baseColorTexture) {
  93594. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93595. babylonMaterial.albedoTexture = texture;
  93596. }));
  93597. }
  93598. if (properties.metallicRoughnessTexture) {
  93599. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93600. babylonMaterial.metallicTexture = texture;
  93601. }));
  93602. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93603. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93604. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93605. }
  93606. }
  93607. this._loadMaterialAlphaProperties(context, material);
  93608. return Promise.all(promises).then(function () { });
  93609. };
  93610. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  93611. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  93612. if (promise) {
  93613. return promise;
  93614. }
  93615. material._babylonMeshes = material._babylonMeshes || [];
  93616. material._babylonMeshes.push(babylonMesh);
  93617. if (!material._loaded) {
  93618. var promises = new Array();
  93619. var babylonMaterial = this._createMaterial(material);
  93620. material._babylonMaterial = babylonMaterial;
  93621. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93622. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93623. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93624. material._loaded = Promise.all(promises).then(function () { });
  93625. }
  93626. assign(material._babylonMaterial);
  93627. return material._loaded;
  93628. };
  93629. GLTFLoader.prototype._createMaterial = function (material) {
  93630. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93631. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93632. return babylonMaterial;
  93633. };
  93634. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93635. var promises = new Array();
  93636. var babylonMaterial = material._babylonMaterial;
  93637. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93638. if (material.doubleSided) {
  93639. babylonMaterial.backFaceCulling = false;
  93640. babylonMaterial.twoSidedLighting = true;
  93641. }
  93642. if (material.normalTexture) {
  93643. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93644. babylonMaterial.bumpTexture = texture;
  93645. }));
  93646. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93647. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93648. if (material.normalTexture.scale != undefined) {
  93649. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93650. }
  93651. }
  93652. if (material.occlusionTexture) {
  93653. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93654. babylonMaterial.ambientTexture = texture;
  93655. }));
  93656. babylonMaterial.useAmbientInGrayScale = true;
  93657. if (material.occlusionTexture.strength != undefined) {
  93658. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93659. }
  93660. }
  93661. if (material.emissiveTexture) {
  93662. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  93663. babylonMaterial.emissiveTexture = texture;
  93664. }));
  93665. }
  93666. return Promise.all(promises).then(function () { });
  93667. };
  93668. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  93669. var babylonMaterial = material._babylonMaterial;
  93670. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  93671. switch (alphaMode) {
  93672. case "OPAQUE" /* OPAQUE */: {
  93673. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93674. break;
  93675. }
  93676. case "MASK" /* MASK */: {
  93677. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  93678. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  93679. if (babylonMaterial.alpha) {
  93680. if (babylonMaterial.alpha === 0) {
  93681. babylonMaterial.alphaCutOff = 1;
  93682. }
  93683. else {
  93684. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  93685. }
  93686. babylonMaterial.alpha = 1;
  93687. }
  93688. if (babylonMaterial.albedoTexture) {
  93689. babylonMaterial.albedoTexture.hasAlpha = true;
  93690. }
  93691. break;
  93692. }
  93693. case "BLEND" /* BLEND */: {
  93694. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  93695. if (babylonMaterial.albedoTexture) {
  93696. babylonMaterial.albedoTexture.hasAlpha = true;
  93697. babylonMaterial.useAlphaFromAlbedoTexture = true;
  93698. }
  93699. break;
  93700. }
  93701. default: {
  93702. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  93703. }
  93704. }
  93705. };
  93706. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  93707. var _this = this;
  93708. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  93709. context = "#/textures/" + textureInfo.index;
  93710. var promises = new Array();
  93711. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  93712. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  93713. var deferred = new BABYLON.Deferred();
  93714. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  93715. if (!_this._disposed) {
  93716. deferred.resolve();
  93717. }
  93718. }, function (message, exception) {
  93719. if (!_this._disposed) {
  93720. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  93721. }
  93722. });
  93723. promises.push(deferred.promise);
  93724. babylonTexture.name = texture.name || "texture" + texture._index;
  93725. babylonTexture.wrapU = samplerData.wrapU;
  93726. babylonTexture.wrapV = samplerData.wrapV;
  93727. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  93728. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  93729. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  93730. babylonTexture.updateURL(objectURL);
  93731. }));
  93732. assign(babylonTexture);
  93733. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  93734. return Promise.all(promises).then(function () { });
  93735. };
  93736. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  93737. if (!sampler._data) {
  93738. sampler._data = {
  93739. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  93740. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  93741. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  93742. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  93743. };
  93744. }
  93745. ;
  93746. return sampler._data;
  93747. };
  93748. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  93749. if (image._objectURL) {
  93750. return image._objectURL;
  93751. }
  93752. var promise;
  93753. if (image.uri) {
  93754. promise = this._loadUriAsync(context, image.uri);
  93755. }
  93756. else {
  93757. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  93758. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  93759. }
  93760. image._objectURL = promise.then(function (data) {
  93761. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  93762. });
  93763. return image._objectURL;
  93764. };
  93765. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  93766. var _this = this;
  93767. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  93768. if (promise) {
  93769. return promise;
  93770. }
  93771. if (!GLTFLoader._ValidateUri(uri)) {
  93772. throw new Error(context + ": Uri '" + uri + "' is invalid");
  93773. }
  93774. if (BABYLON.Tools.IsBase64(uri)) {
  93775. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  93776. }
  93777. return new Promise(function (resolve, reject) {
  93778. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  93779. if (!_this._disposed) {
  93780. resolve(new Uint8Array(data));
  93781. }
  93782. }, function (event) {
  93783. if (!_this._disposed) {
  93784. try {
  93785. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  93786. request._lengthComputable = event.lengthComputable;
  93787. request._loaded = event.loaded;
  93788. request._total = event.total;
  93789. _this._onProgress();
  93790. }
  93791. }
  93792. catch (e) {
  93793. reject(e);
  93794. }
  93795. }
  93796. }, _this._babylonScene.database, true, function (request, exception) {
  93797. if (!_this._disposed) {
  93798. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  93799. }
  93800. });
  93801. _this._requests.push(request);
  93802. });
  93803. };
  93804. GLTFLoader.prototype._onProgress = function () {
  93805. if (!this._progressCallback) {
  93806. return;
  93807. }
  93808. var lengthComputable = true;
  93809. var loaded = 0;
  93810. var total = 0;
  93811. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93812. var request = _a[_i];
  93813. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  93814. return;
  93815. }
  93816. lengthComputable = lengthComputable && request._lengthComputable;
  93817. loaded += request._loaded;
  93818. total += request._total;
  93819. }
  93820. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  93821. };
  93822. GLTFLoader._GetProperty = function (context, array, index) {
  93823. if (!array || index == undefined || !array[index]) {
  93824. throw new Error(context + ": Failed to find index (" + index + ")");
  93825. }
  93826. return array[index];
  93827. };
  93828. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  93829. // Set defaults if undefined
  93830. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  93831. switch (mode) {
  93832. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93833. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93834. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93835. default:
  93836. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  93837. return BABYLON.Texture.WRAP_ADDRESSMODE;
  93838. }
  93839. };
  93840. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  93841. // Set defaults if undefined
  93842. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  93843. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  93844. if (magFilter === 9729 /* LINEAR */) {
  93845. switch (minFilter) {
  93846. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  93847. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  93848. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  93849. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  93850. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  93851. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93852. default:
  93853. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  93854. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93855. }
  93856. }
  93857. else {
  93858. if (magFilter !== 9728 /* NEAREST */) {
  93859. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  93860. }
  93861. switch (minFilter) {
  93862. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  93863. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  93864. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93865. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  93866. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  93867. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  93868. default:
  93869. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  93870. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93871. }
  93872. }
  93873. };
  93874. GLTFLoader._GetNumComponents = function (context, type) {
  93875. switch (type) {
  93876. case "SCALAR": return 1;
  93877. case "VEC2": return 2;
  93878. case "VEC3": return 3;
  93879. case "VEC4": return 4;
  93880. case "MAT2": return 4;
  93881. case "MAT3": return 9;
  93882. case "MAT4": return 16;
  93883. }
  93884. throw new Error(context + ": Invalid type (" + type + ")");
  93885. };
  93886. GLTFLoader._ValidateUri = function (uri) {
  93887. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  93888. };
  93889. GLTFLoader.prototype._compileMaterialsAsync = function () {
  93890. var promises = new Array();
  93891. if (this._gltf.materials) {
  93892. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  93893. var material = _a[_i];
  93894. var babylonMaterial = material._babylonMaterial;
  93895. var babylonMeshes = material._babylonMeshes;
  93896. if (babylonMaterial && babylonMeshes) {
  93897. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  93898. var babylonMesh = babylonMeshes_1[_b];
  93899. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  93900. if (this.useClipPlane) {
  93901. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  93902. }
  93903. }
  93904. }
  93905. }
  93906. }
  93907. return Promise.all(promises).then(function () { });
  93908. };
  93909. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  93910. var promises = new Array();
  93911. var lights = this._babylonScene.lights;
  93912. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  93913. var light = lights_1[_i];
  93914. var generator = light.getShadowGenerator();
  93915. if (generator) {
  93916. promises.push(generator.forceCompilationAsync());
  93917. }
  93918. }
  93919. return Promise.all(promises).then(function () { });
  93920. };
  93921. GLTFLoader.prototype._clear = function () {
  93922. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93923. var request = _a[_i];
  93924. request.abort();
  93925. }
  93926. this._requests.length = 0;
  93927. if (this._gltf && this._gltf.images) {
  93928. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  93929. var image = _c[_b];
  93930. if (image._objectURL) {
  93931. image._objectURL.then(function (value) {
  93932. URL.revokeObjectURL(value);
  93933. });
  93934. image._objectURL = undefined;
  93935. }
  93936. }
  93937. }
  93938. delete this._gltf;
  93939. delete this._babylonScene;
  93940. this._completePromises.length = 0;
  93941. for (var name_3 in this._extensions) {
  93942. this._extensions[name_3].dispose();
  93943. }
  93944. this._extensions = {};
  93945. delete this._rootBabylonMesh;
  93946. delete this._progressCallback;
  93947. this.onMeshLoadedObservable.clear();
  93948. this.onTextureLoadedObservable.clear();
  93949. this.onMaterialLoadedObservable.clear();
  93950. };
  93951. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  93952. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93953. var name_4 = _a[_i];
  93954. var extension = this._extensions[name_4];
  93955. if (extension.enabled) {
  93956. var promise = actionAsync(extension);
  93957. if (promise) {
  93958. return promise;
  93959. }
  93960. }
  93961. }
  93962. return null;
  93963. };
  93964. GLTFLoader._Names = new Array();
  93965. GLTFLoader._Factories = {};
  93966. return GLTFLoader;
  93967. }());
  93968. GLTF2.GLTFLoader = GLTFLoader;
  93969. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  93970. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93971. })(BABYLON || (BABYLON = {}));
  93972. //# sourceMappingURL=babylon.glTFLoader.js.map
  93973. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93974. var BABYLON;
  93975. (function (BABYLON) {
  93976. var GLTF2;
  93977. (function (GLTF2) {
  93978. var GLTFLoaderExtension = /** @class */ (function () {
  93979. function GLTFLoaderExtension(loader) {
  93980. this.enabled = true;
  93981. this._loader = loader;
  93982. }
  93983. GLTFLoaderExtension.prototype.dispose = function () {
  93984. delete this._loader;
  93985. };
  93986. // #region Overridable Methods
  93987. /** Override this method to modify the default behavior for loading scenes. */
  93988. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  93989. /** Override this method to modify the default behavior for loading nodes. */
  93990. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  93991. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  93992. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  93993. /** Override this method to modify the default behavior for loading materials. */
  93994. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  93995. /** Override this method to modify the default behavior for loading uris. */
  93996. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  93997. // #endregion
  93998. /** Helper method called by a loader extension to load an glTF extension. */
  93999. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  94000. if (!property.extensions) {
  94001. return null;
  94002. }
  94003. var extensions = property.extensions;
  94004. var extension = extensions[this.name];
  94005. if (!extension) {
  94006. return null;
  94007. }
  94008. // Clear out the extension before executing the action to avoid recursing into the same property.
  94009. delete extensions[this.name];
  94010. try {
  94011. return actionAsync(context + "/extensions/" + this.name, extension);
  94012. }
  94013. finally {
  94014. // Restore the extension after executing the action.
  94015. extensions[this.name] = extension;
  94016. }
  94017. };
  94018. /** Helper method called by the loader to allow extensions to override loading scenes. */
  94019. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  94020. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  94021. };
  94022. /** Helper method called by the loader to allow extensions to override loading nodes. */
  94023. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  94024. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  94025. };
  94026. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  94027. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  94028. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  94029. };
  94030. /** Helper method called by the loader to allow extensions to override loading materials. */
  94031. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  94032. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  94033. };
  94034. /** Helper method called by the loader to allow extensions to override loading uris. */
  94035. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  94036. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  94037. };
  94038. return GLTFLoaderExtension;
  94039. }());
  94040. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  94041. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94042. })(BABYLON || (BABYLON = {}));
  94043. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  94044. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94045. var BABYLON;
  94046. (function (BABYLON) {
  94047. var GLTF2;
  94048. (function (GLTF2) {
  94049. var Extensions;
  94050. (function (Extensions) {
  94051. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  94052. var NAME = "MSFT_lod";
  94053. var MSFT_lod = /** @class */ (function (_super) {
  94054. __extends(MSFT_lod, _super);
  94055. function MSFT_lod() {
  94056. var _this = _super !== null && _super.apply(this, arguments) || this;
  94057. _this.name = NAME;
  94058. /**
  94059. * Maximum number of LODs to load, starting from the lowest LOD.
  94060. */
  94061. _this.maxLODsToLoad = Number.MAX_VALUE;
  94062. _this._loadingNodeLOD = null;
  94063. _this._loadNodeSignals = {};
  94064. _this._loadingMaterialLOD = null;
  94065. _this._loadMaterialSignals = {};
  94066. return _this;
  94067. }
  94068. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  94069. var _this = this;
  94070. return this._loadExtensionAsync(context, node, function (context, extension) {
  94071. var firstPromise;
  94072. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  94073. var _loop_1 = function (indexLOD) {
  94074. var nodeLOD = nodeLODs[indexLOD];
  94075. if (indexLOD !== 0) {
  94076. _this._loadingNodeLOD = nodeLOD;
  94077. if (!_this._loadNodeSignals[nodeLOD._index]) {
  94078. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  94079. }
  94080. }
  94081. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  94082. if (indexLOD !== 0) {
  94083. var previousNodeLOD = nodeLODs[indexLOD - 1];
  94084. if (previousNodeLOD._babylonMesh) {
  94085. previousNodeLOD._babylonMesh.dispose();
  94086. delete previousNodeLOD._babylonMesh;
  94087. }
  94088. }
  94089. if (indexLOD !== nodeLODs.length - 1) {
  94090. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  94091. if (_this._loadNodeSignals[nodeIndex]) {
  94092. _this._loadNodeSignals[nodeIndex].resolve();
  94093. delete _this._loadNodeSignals[nodeIndex];
  94094. }
  94095. }
  94096. });
  94097. if (indexLOD === 0) {
  94098. firstPromise = promise;
  94099. }
  94100. else {
  94101. _this._loader._completePromises.push(promise);
  94102. _this._loadingNodeLOD = null;
  94103. }
  94104. };
  94105. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  94106. _loop_1(indexLOD);
  94107. }
  94108. return firstPromise;
  94109. });
  94110. };
  94111. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94112. var _this = this;
  94113. // Don't load material LODs if already loading a node LOD.
  94114. if (this._loadingNodeLOD) {
  94115. return null;
  94116. }
  94117. return this._loadExtensionAsync(context, material, function (context, extension) {
  94118. var firstPromise;
  94119. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  94120. var _loop_2 = function (indexLOD) {
  94121. var materialLOD = materialLODs[indexLOD];
  94122. if (indexLOD !== 0) {
  94123. _this._loadingMaterialLOD = materialLOD;
  94124. if (!_this._loadMaterialSignals[materialLOD._index]) {
  94125. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  94126. }
  94127. }
  94128. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  94129. if (indexLOD !== 0) {
  94130. assign(materialLOD._babylonMaterial);
  94131. var previousMaterialLOD = materialLODs[indexLOD - 1];
  94132. if (previousMaterialLOD._babylonMaterial) {
  94133. previousMaterialLOD._babylonMaterial.dispose();
  94134. delete previousMaterialLOD._babylonMaterial;
  94135. }
  94136. }
  94137. if (indexLOD !== materialLODs.length - 1) {
  94138. var materialIndex = materialLODs[indexLOD + 1]._index;
  94139. if (_this._loadMaterialSignals[materialIndex]) {
  94140. _this._loadMaterialSignals[materialIndex].resolve();
  94141. delete _this._loadMaterialSignals[materialIndex];
  94142. }
  94143. }
  94144. });
  94145. if (indexLOD === 0) {
  94146. firstPromise = promise;
  94147. }
  94148. else {
  94149. _this._loader._completePromises.push(promise);
  94150. _this._loadingMaterialLOD = null;
  94151. }
  94152. };
  94153. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  94154. _loop_2(indexLOD);
  94155. }
  94156. return firstPromise;
  94157. });
  94158. };
  94159. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  94160. var _this = this;
  94161. // Defer the loading of uris if loading a material or node LOD.
  94162. if (this._loadingMaterialLOD) {
  94163. var index = this._loadingMaterialLOD._index;
  94164. return this._loadMaterialSignals[index].promise.then(function () {
  94165. return _this._loader._loadUriAsync(context, uri);
  94166. });
  94167. }
  94168. else if (this._loadingNodeLOD) {
  94169. var index = this._loadingNodeLOD._index;
  94170. return this._loadNodeSignals[index].promise.then(function () {
  94171. return _this._loader._loadUriAsync(context, uri);
  94172. });
  94173. }
  94174. return null;
  94175. };
  94176. /**
  94177. * Gets an array of LOD properties from lowest to highest.
  94178. */
  94179. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  94180. if (this.maxLODsToLoad <= 0) {
  94181. throw new Error("maxLODsToLoad must be greater than zero");
  94182. }
  94183. var properties = new Array();
  94184. for (var i = ids.length - 1; i >= 0; i--) {
  94185. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  94186. if (properties.length === this.maxLODsToLoad) {
  94187. return properties;
  94188. }
  94189. }
  94190. properties.push(property);
  94191. return properties;
  94192. };
  94193. return MSFT_lod;
  94194. }(GLTF2.GLTFLoaderExtension));
  94195. Extensions.MSFT_lod = MSFT_lod;
  94196. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  94197. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94198. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94199. })(BABYLON || (BABYLON = {}));
  94200. //# sourceMappingURL=MSFT_lod.js.map
  94201. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94202. var BABYLON;
  94203. (function (BABYLON) {
  94204. var GLTF2;
  94205. (function (GLTF2) {
  94206. var Extensions;
  94207. (function (Extensions) {
  94208. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  94209. var NAME = "KHR_draco_mesh_compression";
  94210. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  94211. __extends(KHR_draco_mesh_compression, _super);
  94212. function KHR_draco_mesh_compression(loader) {
  94213. var _this = _super.call(this, loader) || this;
  94214. _this.name = NAME;
  94215. _this._dracoCompression = null;
  94216. // Disable extension if decoder is not available.
  94217. if (!BABYLON.DracoCompression.DecoderUrl) {
  94218. _this.enabled = false;
  94219. }
  94220. return _this;
  94221. }
  94222. KHR_draco_mesh_compression.prototype.dispose = function () {
  94223. if (this._dracoCompression) {
  94224. this._dracoCompression.dispose();
  94225. }
  94226. _super.prototype.dispose.call(this);
  94227. };
  94228. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94229. var _this = this;
  94230. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  94231. if (primitive.mode != undefined) {
  94232. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  94233. primitive.mode !== 4 /* TRIANGLES */) {
  94234. throw new Error(context + ": Unsupported mode " + primitive.mode);
  94235. }
  94236. // TODO: handle triangle strips
  94237. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  94238. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  94239. }
  94240. }
  94241. var attributes = {};
  94242. var loadAttribute = function (name, kind) {
  94243. var uniqueId = extension.attributes[name];
  94244. if (uniqueId == undefined) {
  94245. return;
  94246. }
  94247. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94248. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94249. babylonMesh._delayInfo.push(kind);
  94250. }
  94251. attributes[kind] = uniqueId;
  94252. };
  94253. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94254. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94255. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94256. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94257. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94258. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94259. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94260. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94261. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  94262. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  94263. try {
  94264. if (!_this._dracoCompression) {
  94265. _this._dracoCompression = new BABYLON.DracoCompression();
  94266. }
  94267. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  94268. }
  94269. catch (e) {
  94270. throw new Error(context + ": " + e.message);
  94271. }
  94272. });
  94273. });
  94274. };
  94275. return KHR_draco_mesh_compression;
  94276. }(GLTF2.GLTFLoaderExtension));
  94277. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  94278. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  94279. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94280. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94281. })(BABYLON || (BABYLON = {}));
  94282. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  94283. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94284. var BABYLON;
  94285. (function (BABYLON) {
  94286. var GLTF2;
  94287. (function (GLTF2) {
  94288. var Extensions;
  94289. (function (Extensions) {
  94290. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  94291. var NAME = "KHR_materials_pbrSpecularGlossiness";
  94292. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  94293. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  94294. function KHR_materials_pbrSpecularGlossiness() {
  94295. var _this = _super !== null && _super.apply(this, arguments) || this;
  94296. _this.name = NAME;
  94297. return _this;
  94298. }
  94299. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94300. var _this = this;
  94301. return this._loadExtensionAsync(context, material, function (context, extension) {
  94302. material._babylonMeshes = material._babylonMeshes || [];
  94303. material._babylonMeshes.push(babylonMesh);
  94304. if (!material._loaded) {
  94305. var promises = new Array();
  94306. var babylonMaterial = _this._loader._createMaterial(material);
  94307. material._babylonMaterial = babylonMaterial;
  94308. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  94309. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  94310. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94311. material._loaded = Promise.all(promises).then(function () { });
  94312. }
  94313. assign(material._babylonMaterial);
  94314. return material._loaded;
  94315. });
  94316. };
  94317. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  94318. var promises = new Array();
  94319. var babylonMaterial = material._babylonMaterial;
  94320. if (properties.diffuseFactor) {
  94321. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  94322. babylonMaterial.alpha = properties.diffuseFactor[3];
  94323. }
  94324. else {
  94325. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94326. }
  94327. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  94328. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  94329. if (properties.diffuseTexture) {
  94330. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  94331. babylonMaterial.albedoTexture = texture;
  94332. }));
  94333. }
  94334. if (properties.specularGlossinessTexture) {
  94335. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  94336. babylonMaterial.reflectivityTexture = texture;
  94337. }));
  94338. babylonMaterial.reflectivityTexture.hasAlpha = true;
  94339. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  94340. }
  94341. this._loader._loadMaterialAlphaProperties(context, material);
  94342. return Promise.all(promises).then(function () { });
  94343. };
  94344. return KHR_materials_pbrSpecularGlossiness;
  94345. }(GLTF2.GLTFLoaderExtension));
  94346. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  94347. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  94348. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94349. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94350. })(BABYLON || (BABYLON = {}));
  94351. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  94352. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94353. var BABYLON;
  94354. (function (BABYLON) {
  94355. var GLTF2;
  94356. (function (GLTF2) {
  94357. var Extensions;
  94358. (function (Extensions) {
  94359. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  94360. var NAME = "KHR_lights";
  94361. var LightType;
  94362. (function (LightType) {
  94363. LightType["AMBIENT"] = "ambient";
  94364. LightType["DIRECTIONAL"] = "directional";
  94365. LightType["POINT"] = "point";
  94366. LightType["SPOT"] = "spot";
  94367. })(LightType || (LightType = {}));
  94368. var KHR_lights = /** @class */ (function (_super) {
  94369. __extends(KHR_lights, _super);
  94370. function KHR_lights() {
  94371. var _this = _super !== null && _super.apply(this, arguments) || this;
  94372. _this.name = NAME;
  94373. return _this;
  94374. }
  94375. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  94376. var _this = this;
  94377. return this._loadExtensionAsync(context, scene, function (context, extension) {
  94378. var promise = _this._loader._loadSceneAsync(context, scene);
  94379. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94380. if (light.type !== LightType.AMBIENT) {
  94381. throw new Error(context + ": Only ambient lights are allowed on a scene");
  94382. }
  94383. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  94384. return promise;
  94385. });
  94386. };
  94387. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  94388. var _this = this;
  94389. return this._loadExtensionAsync(context, node, function (context, extension) {
  94390. var promise = _this._loader._loadNodeAsync(context, node);
  94391. var babylonLight;
  94392. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94393. var name = node._babylonMesh.name;
  94394. switch (light.type) {
  94395. case LightType.AMBIENT: {
  94396. throw new Error(context + ": Ambient lights are not allowed on a node");
  94397. }
  94398. case LightType.DIRECTIONAL: {
  94399. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  94400. break;
  94401. }
  94402. case LightType.POINT: {
  94403. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  94404. break;
  94405. }
  94406. case LightType.SPOT: {
  94407. var spotLight = light;
  94408. // TODO: support inner and outer cone angles
  94409. //const innerConeAngle = spotLight.innerConeAngle || 0;
  94410. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  94411. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  94412. break;
  94413. }
  94414. default: {
  94415. throw new Error(context + ": Invalid light type (" + light.type + ")");
  94416. }
  94417. }
  94418. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  94419. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  94420. babylonLight.parent = node._babylonMesh;
  94421. return promise;
  94422. });
  94423. };
  94424. Object.defineProperty(KHR_lights.prototype, "_lights", {
  94425. get: function () {
  94426. var extensions = this._loader._gltf.extensions;
  94427. if (!extensions || !extensions[this.name]) {
  94428. throw new Error("#/extensions: '" + this.name + "' not found");
  94429. }
  94430. var extension = extensions[this.name];
  94431. return extension.lights;
  94432. },
  94433. enumerable: true,
  94434. configurable: true
  94435. });
  94436. return KHR_lights;
  94437. }(GLTF2.GLTFLoaderExtension));
  94438. Extensions.KHR_lights = KHR_lights;
  94439. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  94440. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94441. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94442. })(BABYLON || (BABYLON = {}));
  94443. //# sourceMappingURL=KHR_lights.js.map
  94444. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94445. globalObject["BABYLON"] = BABYLON
  94446. return BABYLON;
  94447. });